json.decodeFile()

类型 函数
类库 json.*
返回类型
修订 版本 2024.3703
关键字 json
参见 json.decode()

概述

解码预期包含JSON 编码数据的某个文件内容,并返回一个包含相应数据的 Lua 对象(

)。如果数据成功解码,则返回值为一个 Lua 对象;如果出现错误,则返回值为三个值:nil、不属于对象的下一个字符的位置以及错误消息。错误可能与打开文件的问题或 JSON 语法问题相关。

疑难解答

filename 参数通常应从 system.pathForFile() 获取,因此可以将其正确地定位在应用程序的沙盒中。请参见下面的示例

语法

json.decodeFile( filename [, position [, nullval]] )
filename (必需)

字符串包含 JSON 数据的文件的名称。

position (非必需)

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

nullval (非必需)

值为 json.null 的项的返回值(请参见 json.encode()).如果数据包含为“null”但需要了解其存在(在 Lua 中,值为空的表项通常不存在)的项,此项很有用。

示例

local json = require( "json" )

local filename = system.pathForFile( "datafile.json", system.ResourceDirectory )
local decoded, pos, msg = json.decodeFile( filename )

if not decoded then
    print( "Decode failed at "..tostring(pos)..": "..tostring(msg) )
else
    print( "File successfully decoded!" )
end