Last modified 9 years ago Last modified on 2010-03-04 17:09:54


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'} } ))


[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)
print ("Primes are:")
for i,v in ipairs (o.primes) do
    print (i,v)


one		1
two		2
primes		table: 0032B928
Primes are:
1		2
2		3
3		5
4		7

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


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:


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.