JSON

json.format

解析并重新编码 JSON 以标准化格式。

语法

json.format(json: string, encodeOptions?: EncodeOptions, decodeOptions?: DecodeOptions): string

参数

名称类型描述
jsonstring要解析、格式化、缩小或验证的 JSON 字符串。
encodeOptions?EncodeOptions可选的编码设置,例如漂亮的输出或密钥排序。
decodeOptions?DecodeOptions读取 JSON 时使用的可选解析设置。

返回值

名称类型描述
formattedstring格式化的 JSON 字符串。

说明

解析并重新编码 JSON 以标准化格式。

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

返回 formatted (string)。使用返回表区分成功值、nil 结果和可恢复错误。

示例

将现有 JSON 规范化为可读的表示形式。

local compact = '{"b":2,"a":1}'
local formatted = json.format(compact, {
    pretty = true,
    sortKeys = true,
})

print(formatted)

类型

EncodeOptions

控制 JSON 序列化和格式设置。

pretty? boolean 启用格式化的多行 JSON 输出。sortKeys? boolean 在编码之前对对象键进行排序。emptyTableAsArray? boolean 将空表编码为数组而不是对象。errorOnUnsupported? boolean 引发错误而不是替换不受支持的值。encodeInvalidNumbersAsNull? boolean 将 NaN 和无限数编码为 JSON null。maxDepth? integer 设置最大嵌套深度,范围为 1 到 4096。indent? string 设置缩进字符串,限制为 32 个字符。

DecodeOptions

控制 JSON 解析行为。

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