OpenResty 使用 cjson 操作 JSON 数据

OpenResty Lua JSON About 1,167 words

项目说明

OpenResty中的cjson库可以完成JSON数据的编码解码等工作。

cjson有两个模块:cjsoncjson.safe,前者在解析失败后会抛出异常,而后者则返回nil

文档地址:https://github.com/openresty/lua-cjson

代码示例

编码

table序列化为字符串

local json = require "cjson.safe"

json.encode({
        code = 0,
        msg = "请求成功"
})

输出json

{
    "code":0,
    "msg":"请求成功"
}

解码

将字符串转换为table

local json = require "cjson.safe"

json.decode([[{"code":0,"msg":"请求成功"}]])

输出table

{
    code = 0,
    msg = "请求成功"
}

table

encode_empty_table_as_object:默认为true,默认会将空的table对象序列化为JSON对象。

local json = require "cjson"

json.encode({
    foo = "bar",
    some_object = {}
})

输出json

{
    "some_object": {},
    "foo": "bar"
}

JSON数组

json.empty_array:序列化空数组

local json = require "cjson"

json.encode({
    foo = "bar",
    some_object = {},
    some_array = json.empty_array
})

输出json

{
    "some_object": {},
    "foo": "bar",
    "some_array": []
}

其他方法

  • array_mt:将table序列化为JSON数组
  • empty_array_mt:使json.encode()(不传任何参数),序列化为JSON数组
  • decode_array_with_array_mt:解码为一个数组
  • encode_number_precision:设置数字的精确度,最多16个字符
  • encode_keep_ buffer:复用缓存提高性能,默认是true
  • encode_max_depth:编码的深度,默认是1000
  • decode_max_depth:解码的深度,默认是1000

开源案例

https://github.com/fendoudebb/z-blog-openresty

Views: 7,533 · Posted: 2020-03-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh