json.encode()

类型 函数
json.*
返回值 字符串
版本 版本 2024.3703
关键字 json
另请参见 json.decode()

概述

将 Lua 对象(表格)作为 JSON 编码的字符串返回。由于 Lua 表格中值为 nil 的项实际上并不存在,所以如果你需要保留 JSON 中的数组索引,你应使用 json.null 作为占位符(请参阅 json.decode() 中关于 nullval 的论述)。

语法

json.encode( t [, options] )
t (必需)

表格. Lua 表格。

options (可选)

表格. 包含 JSON 库可选指令的 Lua 表格

  • indent — 设置为 true 以生成格式化的 JSON 输出。
  • exception — 调用以处理不支持的数据类型。参数为 reasonvaluestatedefaultmessage。返回一个要包含在输出中或引发错误的 nil 字符串。默认情况下,Corona 将不支持的值处理为字符串。

转换

  1. 可编码的 Lua 类型包括 字符串数字布尔值表格nil
  2. 不可编码的类型在输出中显示为描述性字符串。
  3. 所有控制字符都编码为 \uXXXX 格式,例如 "\021" 编码为 "\u0015"
  4. 所有 JSON \uXXXX 字符都解码为字符(仅 0-255 字节范围)。
  5. JSON 单行 ///* */ 块注释在解码期间被丢弃。
  6. 按数字索引的 Lua 数组编码为 JSON 列表,例如 [1,2,3]
  7. Lua 词典表转换为 JSON 对象,例如 {"one":1,"two":2}
  8. 默认情况下,JSON Null 值解码为 Lua 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"
}