Type Function Library json.* Return value String Revision 2017.3060 Keywords json See also json.decode()
Returns the Lua object (table) as a JSON-encoded string. Since items with nil
values in a Lua table effectively don't exist, you should use json.null
as a placeholder value if you need to preserve array indices in your JSON (see discussion of nullval
in json.decode()).
json.encode( t [, options] )
Table. Lua table.
Table. Lua table containing optional directives to the JSON library:
indent
— set to true
to produce formatted JSON output.exception
— function called to handle unsupported datatypes. Parameters are reason
, value
, state
and defaultmessage
. Return a string to be included in the output or nil
to raise an error. By default, Corona handles unsupported values as strings.nil
.\uXXXX
format, for example "\021"
encodes to "\u0015"
.\uXXXX
chars are decoded to chars (0
-255
byte range only).//
and /* */
block comments are discarded during decoding.[1,2,3]
.{"one":1,"two":2}
.nil
and treated by Lua in the normal way (for example, they appear not to exist — see json.decode()).local json = require( "json" ) local t = { ["name1"] = "value1", ["name2"] = { 1, false, true, 23.54, "a \021 string" }, name3 = json.null } local encoded = json.encode( t ) print( encoded ) --> {"name1":"value1","name3":null,"name2":[1,false,true,23.54,"a \u0015 string"]} local encoded = json.encode( t, { indent=true } ) print( encoded ) --> { --> "name1":"value1", --> "name3":null, --> "name2":[1,false,true,23.54,"a \u0015 string"] --> } -- Since this was just encoded using the same library it's unlikely to fail -- However, it's good practice to handle errors anyway local decoded, pos, msg = json.decode( encoded ) if not decoded then print( "Decode failed at " .. tostring(pos) .. ": " .. tostring(msg) ) else print( decoded.name2[4] ) --> 23.54 end
local json = require( "json" ) local function onTapLogo( event ) print( "onTapLogo: event: " .. json.encode( event, { indent=true } ) ) end local logo = display.newImageRect( "logo.png", 128, 128 ) logo.x = display.contentCenterX logo.y = display.contentCenterY logo:addEventListener( "tap", onTapLogo )
onTapLogo: event: { "y":175, "x":198, "time":2720.303, "target":{ "_dispatchingEventName":"tap", "_class":{ "removeEventListener":"<type 'function' is not supported by JSON.>", "addEventListener":"<type 'function' is not supported by JSON.>", "__index":"<reference cycle>" }, "_proxy":"<type 'userdata' is not supported by JSON.>", "_functionListeners":{ "tap":["<type 'function' is not supported by JSON.>"] } }, "numTaps":1, "name":"tap" }