跳转至

prettycjson: Lua cJSON 美化格式化器

安装

如果您尚未设置 RPM 仓库订阅,请 注册。然后您可以继续以下步骤。

CentOS/RHEL 7 或 Amazon Linux 2

yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-prettycjson

CentOS/RHEL 8+、Fedora Linux、Amazon Linux 2023

dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-prettycjson

要在 NGINX 中使用此 Lua 库,请确保已安装 nginx-module-lua

本文档描述了 lua-resty-prettycjson v1.6,发布于 2016 年 9 月 29 日。


lua-resty-prettycjson 是一个用于 Lua cJSON 的 JSON 美化格式化器。

Lua API

string function(dt, [lf = "\n", [id = "\t", [ac = " ", [ec = function]]]])

美化格式化 JSON 输出。如果您想使用不同于默认 \n 的换行符,可以传递 lf(换行符)。如果您想用其他字符代替 \t(制表符)进行缩进(id 参数),也可以将其作为参数传递。如果您希望在 JSON 中的冒号 : 后使用其他字符而不是 (单个空格)(ac 参数),您也可以更改,例如尝试 \n。如果您想使用其他编码器而不是 cJSON,可以将编码函数作为第五个参数(ec)传递。它应该接受任何作为输入参数,并且如果编码出现问题,该函数应返回 nil 和错误消息,例如:

nil, "Cannot serialise function: type not supported"

对于输入参数 dt,它接受 cjson.encode 所接受的任何内容(或自定义编码函数所接受的任何内容)。

示例
local pretty = require "resty.prettycjson"

print(pretty({
    key1 = "data",
    key2 = 27,
    key3 = {
        key3_1 = "something",
        key3_2 = "something else"
    },
    key4 = {
        "item1",
        "item2"
    },
    key5 = {},
    key5 = {{''}, {'',''}, {{},{}}},
    key6 = { '' },
    key7 = {{{{ test = "value", {{{{{{}}},{{},{},{}},{},{}}}}}}}}
}))

这将输出:

{
    "key6": [
        ""
    ],
    "key3": {
        "key3_1": "something",
        "key3_2": "something else"
    },
    "key7": [
        [
            [
                {
                    "1": [
                        [
                            [
                                [
                                    [
                                        {}
                                    ]
                                ],
                                [
                                    {},
                                    {},
                                    {}
                                ],
                                {},
                                {}
                            ]
                        ]
                    ],
                    "test": "value"
                }
            ]
        ]
    ],
    "key1": "data",
    "key5": [
        [
            ""
        ],
        [
            "",
            ""
        ],
        [
            {},
            {}
        ]
    ],
    "key2": 27,
    "key4": [
        "item1",
        "item2"
    ]
}

变更

该模块每个版本的变更记录在 Changes.md 文件中。

GitHub

您可以在 nginx-module-prettycjson 的 GitHub 仓库 中找到此模块的其他配置提示和文档。