A Lua wrapper for cJSON.
string cjson.serialize(object)
Serialize a Lua value into JSON string, which can be deserialized by cjson.deserialize()
later.
Convert rule in order:
- A Lua value will always have a key
v
as it's top level key.{ "v": "example" }
- If a value have metatable field
__name
, and metamethod__tostring
, the value of__name
and return value of__tostring
will be the json value.{ "v": { "t": "typename", "p": "payload" } }
- If it is a Lua native type (nil, boolean, number, string), the value is
the equal JSON value:
{ "v": null } { "v": true } { "v": 1.2 } { "v": "hello world" }
- If it is a userdata (at this stage, it does not have metatable), and it
is equal to C value
NULL
, treat it as JSON null.{ "v": null }
- If it is a table, expand it as JSON array. The content in array is a
series of JSON object that have
k
as table key andv
as table value. The value ofk
andv
follows the same convert rule.{ "v": [ { "k": 0, "v": 3 }, { "k": "b", "v": { "t": "typename", "p": "payload"} } ] }
- For other conditions raise an error.
object cjson.deserialize(string)
Deserialize a JSON string into Lua value.
Convert rule in order:
- A Lua value will always have a key
v
as it's top level key. - If the JSON value is
null
,boolean
,number
orstring
, convert it into equal Lua value. - If the JSON value is array, treat it as Lua table.
- If the JSON value is object, treat it as userdata. The
t
specify the type name of userdata. A metamethod__fromstring
will be called withpayload
as it's argument. The return value will be treat it as Lua value.