类型 函数 库 json.* 返回值 表 修订版 版本 2024.3703 关键字 json 另请参阅 json.encode() json.decodeFile()
对 JSON 编码的数据结构进行解码,并返回包含数据的 Lua 对象 (表)。数据成功解码后返回 Lua 对象,或者在出错时返回三个值:nil
,不属于对象的下一个字符的位置和错误消息。
json.decode( data [, position [, nullval]] )
字符串.包含 JSON 数据的字符串。
数字.data
中开始解码的索引(如果省略,则默认为 1
)。
为值等于 json.null
的项返回的值(请参阅 json.encode())。如果您的数据包含“null”的项,但您需要知道这些项的存在(Lua 中,值为 nil
的表项通常不存在),这将非常有用。
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, but 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