美文网首页
空table应该编码为数组 or 对象

空table应该编码为数组 or 对象

作者: Uzero | 来源:发表于2017-09-30 11:48 被阅读0次

Json有两种常用的数据类型:object 和 array

object : 被 {} 包裹的对象

array :被 [] 包裹的数组

看案例

local cjson = require "cjson"

local tab= {}

tab.name= "demo"

tab.likes = {}

local str_encode = cjson.encode(tab)

ngx.say(str_encode)

{"likes":{},"name":"demo"}

cjson对于空的table,会默认处理为object,对于Lua本身,是无法区分空数组和空字典的(数组和字典融合到一起了),但是对于强类型语言(C/C++, Java等),这时候就会出现问题,必须作容错处理

-- 方案一 使用metatable将table标记为array

setmetatable(tab.likes, cjson.empty_array_mt)

ngx.say(cjson.encode(tab)) 

{"likes":[],"name":"demo"}

-- 方案二 使用encode_empty_table_as_object方法

cjson.encode_empty_table_as_object(false)

ngx.say(cjson.encode(tab)) 

{"likes":[],"name":"demo"}

-- 方案三 使用第三方库 dkjson

local dkjson = require "dkjson"

local tab= {}

tab.name= "demo"

tab.likes = {}

local str_encode = dkjson.encode(tab)

ngx.say(str_encode)

{"likes":[],"name":"demo"}

其他(cjson.empty_array)

local cjson = require "cjson"

local json = cjson.encode({    

        foo = "bar",    

        some_object = {},    

        some_array = cjson.empty_array

})

ngx.say(json)

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

相关文章

网友评论

      本文标题:空table应该编码为数组 or 对象

      本文链接:https://www.haomeiwen.com/subject/okjgextx.html