类型 函数 库 json.* 返回值 字符串 版本 版本 2024.3703 关键字 json 另请参见 json.decode()
将 Lua 对象(表格)作为 JSON 编码的字符串返回。由于 Lua 表格中值为 nil 的项实际上并不存在,所以如果你需要保留 JSON 中的数组索引,你应使用 json.null 作为占位符(请参阅 json.decode() 中关于 nullval 的论述)。
json.encode( t [, options] )
表格. Lua 表格。
表格. 包含 JSON 库可选指令的 Lua 表格
indent — 设置为 true 以生成格式化的 JSON 输出。exception — 调用以处理不支持的数据类型。参数为 reason、value、state 和 defaultmessage。返回一个要包含在输出中或引发错误的 nil 字符串。默认情况下,Corona 将不支持的值处理为字符串。nil。\uXXXX 格式,例如 "\021" 编码为 "\u0015"。\uXXXX 字符都解码为字符(仅 0-255 字节范围)。// 和 /* */ 块注释在解码期间被丢弃。[1,2,3]。{"one":1,"two":2}。nil,并按正常方式由 Lua 处理(例如,它们看似不存在,请参阅 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"
}