json.decode()

类型 函数
json.*
返回值
修订版 版本 2024.3703
关键字 json
另请参阅 json.encode()
json.decodeFile()

概览

对 JSON 编码的数据结构进行解码,并返回包含数据的 Lua 对象 ()。数据成功解码后返回 Lua 对象,或者在出错时返回三个值:nil,不属于对象的下一个字符的位置和错误消息。

语法

json.decode( data [, position [, nullval]] )
data (必需)

字符串.包含 JSON 数据的字符串。

position (可选)

数字.data 中开始解码的索引(如果省略,则默认为 1)。

nullval (可选)

为值等于 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