Changes between Initial Version and Version 1 of JSONLua


Ignore:
Timestamp:
2010-03-04 17:09:54 (10 years ago)
Author:
javier_guerra
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • JSONLua

    v1 v1  
     1 
     2== json.lua == 
     3 
     4Simply copied from [http://json.luaforge.net/ JSON4Lua].  This is only the JSON encoding/decoding part, the JSON-RPC client depend on the (missing) !LuaSocket HTTP module. 
     5 
     6'''`string json.encode( lua_object )`'''[[BR]] 
     7Returns the Lua object JSON encoded into a string. 
     8Example: 
     9{{{ 
     10json = require("json") 
     11print (json.encode( { 1, 2, 'fred', {first='mars',second='venus',third='earth'} } )) 
     12}}} 
     13prints 
     14{{{ 
     15 
     16[1,2,"fred", {"first":"mars","second":"venus","third","earth"}] 
     17}}} 
     18 
     19'''`lua_object json.decode( json_string )`'''[[BR]] 
     20Decodes the JSON encoded data structure, and returns a Lua object with the appropriate data. 
     21Example: 
     22{{{ 
     23json = require("json") 
     24testString = [[ { "one":1 , "two":2, "primes":[2,3,5,7] } ]] 
     25o = json.decode(testString) 
     26for k,v in pairs (o) do 
     27    print (k,v) 
     28end 
     29print ("Primes are:") 
     30for i,v in ipairs (o.primes) do 
     31    print (i,v) 
     32end 
     33}}} 
     34prints: 
     35{{{ 
     36one             1 
     37two             2 
     38primes          table: 0032B928 
     39Primes are: 
     401               2 
     412               3 
     423               5 
     434               7 
     44}}} 
     45 
     46'''`json.null`'''[[BR]] 
     47A unique value that will be encoded as a null in a JSON encoding. 
     48 
     49This 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: 
     50{{{ 
     51t = { user="test", password=nil } 
     52}}} 
     53Since Lua simply discards the password key, JSON4Lua encodes this as the JSON string 
     54{{{ 
     55{"user":"test"} 
     56}}} 
     57If, for some reason, your JSON RPC Server requires a defined `null` value, use the following code: 
     58{{{ 
     59t = { user="test", password=json.null } 
     60}}} 
     61This will now correctly encode to: 
     62{{{ 
     63{"user":"test","password":null} 
     64}}} 
     65Incidentally, `json.null` is simply a function that returns itself, so that you can use either `json.null` or `json.null()` as you fancy. 
     66 
     67'''Note''': A JSON `null` value is decoded as Lua `nil`, not as `json.null`.