【openresty】json模块

1,json介绍
web开发过程中,经常用的数据结构为json,openresty中封装了json模块
openresty如何使用

local json = require("cjson")

json.encode 将表格数据编码为 JSON 字符串
格式:jsonString = json.encode(表格对象)

2,具体案例
2.1 table包含哈希键值对时,数组键值将被转换为字符串键值

local json = require("cjson")
local t = {1,3,name="张三",age="19",address={"地址1","地址2"},sex="女"}
ngx.say(json.encode(t));
ngx.say("<br/>");
# 输出结果
{"1":1,"2":3,"sex":"女","age":"19","address":["地址1","地址2"],"name":"张三"}


local str = json.encode({a=1,[5]=3})
ngx.say(str); ----- {"a":1,"5":3}
ngx.say("<br/>");

2.2 table所有键为数组型键值对时,会当作数组看待,空位将转化为null

local str = json.encode({[3]=1,[5]=2,[6]="3",[7]=4})
ngx.say(str); ---- [null,null,1,null,2,"3",4]
ngx.say("<br/>");

local str = json.encode({[3]=2,[5]=3})
ngx.say(str); ---- [null,null,2,null,3]
ngx.say("<br/>");
发布了192 篇原创文章 · 获赞 18 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/luolinll1212/article/details/103970646
今日推荐