The json.encode function is complete; json.decode is next. I'm really happy with how this is turning out! Here's a brief explanation of what I've done.
json.encode takes Lua data and returns a "compiled" userdata-wrapped json_object. This object has :to_json() and :to_lua() methods. :to_json() will return a valid JSON string, whereas :to_lua() will return a decoded Lua representation. The compiled json objects can also be used as part of later json.encode calls.
Three helpful other items in the json table are json.array, json.object, and json.null. json.array and json.object take a table and return a compiled JSON userdata, treating the table as an array/object and ignoring any invalid keys. json.null is a pre-generated JSON userdata representing null, equivalent to json.encode(nil).
Examples:
chunk = json.encode{1, 2, nil, 4, json.null}
print(chunk:to_json())
--[[
Output:
[1, 2, null, 4, null]
--]]
chunk = json.encode{foo=100, bar=chunk, baz=101}
print(chunk:to_json())
--[[
Output:
{ "baz": 101, "bar": [ 1, 2, null, 4, null ], "foo": 100 }
--]]
print(json.encode{}:to_json())
print(json.encode(json.array{}):to_json())
print(json.encode(json.object{}):to_json())
--[[
Output:
ERROR: Ambiguous, could be array or object.
[ ]
{ }
--]]
* :to_lua() isn't implemented yet, I'll be adding it along with json.decode.
EDIT: It's hard to see the difference between {} and () in the code font, so if you're confused by that, look closely.
EDIT 2: I'm moving this to a thread in the Development forum, so this one can focus on more relevant protocol details. JSON itself is obviously relevant, but less so the integration into MUSHclient. |