harningt / luajson

JSON parser/encoder for Lua Parses JSON using LPEG for speed and flexibility. Depending on parser/encoder options, various values are preserved as best as possible.
http://www.eharning.us/wiki/luajson/
Other
251 stars 48 forks source link

Ordered map decoding of objects? #31

Closed mtdowling closed 10 years ago

mtdowling commented 10 years ago

I often need the JSON data I'm parsing to use ordered maps. Is there any way to specify how maps are created when decoding JSON so that I can use ordered maps rather than unordered Lua tables? I'm not asking for ordered maps in this library, but rather a hook that allows you to control how a map is created (e.g., a function).

For example, Python's json.load() allows you to specify a custom type for decoding objects: https://docs.python.org/2/library/json.html

harningt commented 10 years ago

I suppose an option would be for my code to expose a configuration value that allows you to set a custom constructor for arrays and objects. There is the object.setObjectKey value that you can set in the configuration that you could use to record order.

Ex:

    json.decode.getDecoder({ object = { setObjectKey = function(object, key, value)
        object[#object + 1] = key -- Add key name to 'array portion' of object
        object[key] = value -- Set associated value
    end }})("{testItem:true}")
mtdowling commented 10 years ago

Thanks for the tip. I think I could also do this:

fn = json.decode.getDecoder({
  object = {
    setObjectKey = function (object, key, value)
      local meta = getmetatable(object)
      if not meta then
        meta = {__jsonorder = {}}
        setmetatable(object, meta)
      end
      meta.__jsonorder[#meta.__jsonorder + 1] = key
      object[key] = value
    end
  }
})