编码为 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/lua-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. local json = require("cjson")
  2. --稀疏数组会被处理成object
  3. json.encode_sparse_array(true)
  4. local function _json_encode(data)
  5. return json.encode(data)
  6. end
  7. function json_encode( data, empty_table_as_object )
  8. --Lua的数据类型里面,arraydict是同一个东西。对应到json encode的时候,就会有不同的判断
  9. --cjson对于空的table,就会被处理为object,也就是{}
  10. --处理方法:对于cjson,使用encode_empty_table_as_object这个方法。
  11. json.encode_empty_table_as_object(empty_table_as_object or false) -- 空的table默认为array
  12. local ok, json_value = pcall(_json_encode, data)
  13. if not ok then
  14. return nil
  15. end
  16. return json_value
  17. end

另一种思路是,使用 setmetatable(data, json.empty_array_mt),来标记特定的 table,让 cjson 在编码这个空 table 时把它处理成 array:

  1. local data = {}
  2. setmetatable(data, json.empty_array_mt)
  3. ngx.say("empty array: ", json.encode(data)) -- empty array: []