Json
有两种比较常用的数据类型:被{}
包裹的对象(object
),被[]
包裹的数组(array
)
问题描述
从第三方API
返回的json
数据,存在一个key
的值为空数组,可是经过decode
和encode
这两步操作后,这个key
的值就变为空对象了:
1 2 3 4 5 6 7
| local cjson = require('cjson')
local raw = {} raw.name = 'answer' raw.list = {} local str = cjson.encode(raw) print('after cjson encode:', str)
|
输出:
1
| after cjson encode: {"name":"answer","list":{}}
|
cjson
对于空的table
,会默认处理为object
,对于Lua
本身,是无法区分空数组和空字典的(数组和字典融合到一起了),但是对于强类型语言(C/C++, Java
等),这时候就会出现问题,必须作容错处理
解决方法
使用encode_empty_table_as_object
方法
1 2 3 4 5 6 7 8
| local cjson = require('cjson')
local raw = {} raw.name = 'answer' raw.list = {} cjson.encode_empty_table_as_object(false) local str = cjson.encode(raw) print('after cjson encode:', str)
|
输出:
1
| after cjson encode: {"name":"answer","list":[]}
|
更换dkjson
库
1 2 3 4 5 6 7
| local dkjson = require('dkjson')
local raw = {} raw.name = 'answer' raw.list = {} local str = dkjson.encode(raw) print('after cjson encode:', str)
|
输出:
1
| after cjson encode: {"name":"answer","list":[]}
|
1 2 3 4 5 6 7 8
| local cjson = require('cjson')
local raw = {} raw.name = 'answer' raw.list = {} setmetatable(raw.list, cjson.empty_array_mt) local str = cjson.encode(raw) print('after cjson encode:', str)
|
输出:
1
| after cjson encode: {"name":"answer","list":[]}
|
Reference