跳转至

libcjson: 基于 LuaJIT FFI 的 nginx-module-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-libcjson

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

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

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

本文档描述了 lua-resty-libcjson v1.4,发布于 2016 年 7 月 04 日。


lua-resty-libcjson 是一个基于 LuaJIT FFI 的 cJSON 库(也经过 OpenResty 测试)。

Lua API

mixed json.decode(value)

解码 JSON 值或结构(JSON 数组或对象),并返回 Lua table 或某些简单值(例如 booleanstringnumberniljson.null(在 OpenResty 上下文中,json.nullngx.null 相同)。

示例
local json = require "resty.libcjson"
local obj = json.decode "{}"       -- table (with obj.__jsontype == "object")
local arr = json.decode "[]"       -- table (with arr.__jsontype == "array")
local nbr = json.decode "1"        -- 1
local bln = json.decode "true"     -- true
local str = json.decode '"test"'   -- "test"
local str = json.decode '""'       -- ""
local num = json.decode(5)         -- 5
local num = json.decode(math)      -- math
local num = json.decode(json.null) -- json.null
local nul = json.decode "null"     -- json.null
local nul = json.decode ""         -- nil
local nul = json.decode(nil)       -- nil
local nul = json.decode()          -- nil

嵌套的 JSON 结构被解析为嵌套的 Lua 表。

string json.encode(value, formatted)

编码 Lua 值或表,并返回等效的 JSON 值或结构作为字符串。您可以选择传递 formatted 参数,值为 false,以获得未格式化的 JSON 字符串作为输出。

示例
local json = require "resty.libcjson"
local str = json.encode{}                              -- "[]"
local str = json.encode(setmetatable({}, json.object)) -- "{}"
local str = json.encode(1)                             -- "1"
local str = json.encode(1.1)                           -- "1.100000"
local str = json.encode "test"                         -- '"test"'
local str = json.encode ""                             -- '""'
local str = json.encode(false)                         -- "false"
local str = json.encode(nil)                           -- "null"
local str = json.encode(json.null)                     -- "null"
local str = json.encode()                              -- "null"
local str = json.encode{ a = "b" }                     -- '{ "a": "b" }'
local str = json.encode{ "a", b = 1 }                  -- '{ "1": "a", "b": 1 }'
local str = json.encode{ 1, 1.1, "a", "", false }      -- '[1, 1.100000, "a", "", false]'

嵌套的 Lua 表被编码为嵌套的 JSON 结构(JSON 对象或数组)。

关于 JSON 数组和对象的编码与解码

请参见此评论: https://github.com/bungle/lua-resty-libcjson/issues/1#issuecomment-38567447

基准测试

关于 190 MB 的 citylots.json:

## Lua cJSON
解码时间: 5.882825
编码时间: 4.902301
## lua-resty-libcjson
解码时间: 6.409872
编码时间: (需要很长时间)

GitHub

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