JSON

json.decodeSafe

解析 JSON 而不抛出异常并返回成功、值和错误详细信息。

语法

json.decodeSafe(json: string, options?: DecodeOptions): boolean | any | nil | string | nil | number | nil

参数

名称类型描述
jsonstring要解析、格式化、缩小或验证的 JSON 字符串。
options?DecodeOptions控制操作行为方式的可选设置表。

返回值

名称类型描述
successboolean当操作成功完成时为 true。
decodedany | nil解码的 Luau 值或解码的字节字符串。
errorMessagestring | nil加载或解析失败时返回错误信息,否则返回nil。
errorPositionnumber | nil解析失败的位置,如果没有发生解析错误则为nil。

说明

解析 JSON 而不抛出异常并返回成功、值和错误详细信息。

使用 2 个参数调用: json, options。参数表会说明哪些值必填,哪些值只用于细化行为。

返回 success (boolean), decoded (any | nil), errorMessage (string | nil), errorPosition (number | nil)。使用返回表区分成功值、nil 结果和可恢复错误。

示例

解析不受信任的 JSON 而不会引发错误。

local ok, value, message, position = json.decodeSafe('{"ready":true}')

if ok then
    print(value.ready)
else
    warn(message, position)
end

类型

DecodeOptions

控制 JSON 解析行为。

useNull? boolean 使用库的 null 标记而不是 nil 来表示 JSON null。maxDepth? integer 设置最大嵌套深度,范围为 1 到 4096。