Openresty资料之JSON

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sky6even/article/details/90667010

Openresty使用cjson库操作JSON数据,它采用c语言实现,速度非常快。

cjson库里有两个模块:“cjson”和“cjson.safe”,通常使用后者,它更“安全”一些,当数据格式错误时不会导致LuaVM错误,而是返回nil。

◆ 基本用法:

首先要用require函数加载模块,然后调用encode对数据编码,decode把数据解码为Lua表

local cjson = require "cjson.safe"

local str = cjson.encode(
							{name='jojo', cat='comic'})
							
local obj = cjson.decode(str)

obj = cjson.decode([[{"wrong":"formate"}]])   -- 错误格式的数据,引号不匹配
assert(not obj)                               -- 返回值是nil,不会报错

◆ 功能设置函数:

cjson还有一些功能设置函数,可以调整编码解码的具体行为,常用的有:

encode_empty_table_as_object:空表编码为对象,否则为数组
empty_array:编码时表示一个空数组
encode_number_precision:设置数字的精确度,最多16个字符
encode_keep_ buffer:复用缓存提高性能,默认是true
encode_max_depth:编码的深度,默认是1000
decode_max_depth:解码的深度,默认是1000

用法示例:

cjson.encode_empty_table_as_object(false)  -- 空对象将编码为数组
str = cjson.encode({})               -- 结果是空数组"[]"

cjson.encode_empty_table_as_object(true)  -- 空对象将编码为对象
str = cjson.encode({a={} , b=cjson.empty_ array})  -- 结果是{"a":{},"b":[]}

cjson.encode_number_precision(5)  -- 数字精度改为5
str = cjson.encode({x=math.pi})  -- 结果是{"x":3.1416}

猜你喜欢

转载自blog.csdn.net/sky6even/article/details/90667010
今日推荐