Version 1 (modified by javier_guerra, 15 years ago) (diff) |
---|
json.lua
Simply copied from JSON4Lua. This is only the JSON encoding/decoding part, the JSON-RPC client depend on the (missing) LuaSocket HTTP module.
string json.encode( lua_object )
Returns the Lua object JSON encoded into a string.
Example:
json = require("json") print (json.encode( { 1, 2, 'fred', {first='mars',second='venus',third='earth'} } ))
prints
[1,2,"fred", {"first":"mars","second":"venus","third","earth"}]
lua_object json.decode( json_string )
Decodes the JSON encoded data structure, and returns a Lua object with the appropriate data.
Example:
json = require("json") testString = [[ { "one":1 , "two":2, "primes":[2,3,5,7] } ]] o = json.decode(testString) for k,v in pairs (o) do print (k,v) end print ("Primes are:") for i,v in ipairs (o.primes) do print (i,v) end
prints:
one 1 two 2 primes table: 0032B928 Primes are: 1 2 2 3 3 5 4 7
json.null
A unique value that will be encoded as a null in a JSON encoding.
This is necessary in one situation. In Lua, if a key in a table has a nil value, the key is simply discarded (since any non-existent key has a nil value). The encoding of arrays has been built to manage this nil-values in arrays, but associative arrays provide a problem. Consider:
t = { user="test", password=nil }
Since Lua simply discards the password key, JSON4Lua encodes this as the JSON string
{"user":"test"}
If, for some reason, your JSON RPC Server requires a defined null value, use the following code:
t = { user="test", password=json.null }
This will now correctly encode to:
{"user":"test","password":null}
Incidentally, json.null is simply a function that returns itself, so that you can use either json.null or json.null() as you fancy.
Note: A JSON null value is decoded as Lua nil, not as json.null.