加载中...

空table编码为array还是object


编码为array还是object

首先大家请看这段源码:

  1. -- http://www.kyne.com.au/~mark/software/lua-cjson.php
  2. -- version: 2.1 devel
  3. local json = require("cjson")
  4. ngx.say("value --> ", json.encode({dogs={}}))

输出结果

value --> {"dogs":{}}

注意看下encode后key的值类型,"{}" 代表key的值是个object,"[]" 则代表key的值是个数组。对于强类型语言(c/c++, java等),这时候就有点不爽。因为类型不是他期望的要做容错。对于lua本身,是把数组和字典融合到一起了,所以他是无法区分空数组和空字典的。

参考openresty-cjson中额外贴出测试案例,我们就很容易找到思路了。

  1. -- 内容节选lua-cjson-2.1.0.2/tests/agentzh.t
  2. === TEST 1: empty tables as objects
  3. --- lua
  4. local cjson = require "cjson"
  5. print(cjson.encode({}))
  6. print(cjson.encode({dogs = {}}))
  7. --- out
  8. {}
  9. {"dogs":{}}
  10. === TEST 2: empty tables as arrays
  11. --- lua
  12. local cjson = require "cjson"
  13. cjson.encode_empty_table_as_object(false)
  14. print(cjson.encode({}))
  15. print(cjson.encode({dogs = {}}))
  16. --- out
  17. []
  18. {"dogs":[]}

综合本章节提到的各种问题,我们可以封装一个json encode的示例函数:

  1. function json_encode( data, empty_table_as_object )
  2. --lua的数据类型里面,arraydict是同一个东西。对应到json encode的时候,就会有不同的判断
  3. --对于linux,我们用的是cjson库:A Lua table with only positive integer keys of type number will be encoded as a JSON array. All other tables will be encoded as a JSON object.
  4. --cjson对于空的table,就会被处理为object,也就是{}
  5. --dkjson默认对空table会处理为array,也就是[]
  6. --处理方法:对于cjson,使用encode_empty_table_as_object这个方法。文档里面没有,看源码
  7. --对于dkjson,需要设置meta信息。local a= {};a.s = {};a.b='中文';setmetatable(a.s, { __jsontype = 'object' });ngx.say(comm.json_encode(a))
  8. local json_value = nil
  9. if json.encode_empty_table_as_object then
  10. json.encode_empty_table_as_object(empty_table_as_object or false) -- 空的table默认为array
  11. end
  12. if require("ffi").os ~= "Windows" then
  13. json.encode_sparse_array(true)
  14. end
  15. pcall(function (data) json_value = json.encode(data) end, data)
  16. return json_value
  17. end

还没有评论.