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