# 編碼為array還是object
首先大家請看這段源碼:
~~~
-- http://www.kyne.com.au/~mark/software/lua-cjson.php
-- version: 2.1 devel
local json = require("cjson")
ngx.say("value --> ", json.encode({dogs={}}))
~~~
輸出結果
> value --> {"dogs":{}}
注意看下encode后key的值類型,"{}" 代表key的值是個object,"[]" 則代表key的值是個數組。對于強類型語言(c/c++, java等),這時候就有點不爽。因為類型不是他期望的要做容錯。對于lua本身,是把數組和字典融合到一起了,所以他是無法區分空數組和空字典的。
參考openresty-cjson中額外貼出測試案例,我們就很容易找到思路了。
~~~
-- 內容節選lua-cjson-2.1.0.2/tests/agentzh.t
=== TEST 1: empty tables as objects
--- lua
local cjson = require "cjson"
print(cjson.encode({}))
print(cjson.encode({dogs = {}}))
--- out
{}
{"dogs":{}}
=== TEST 2: empty tables as arrays
--- lua
local cjson = require "cjson"
cjson.encode_empty_table_as_object(false)
print(cjson.encode({}))
print(cjson.encode({dogs = {}}))
--- out
[]
{"dogs":[]}
~~~
綜合本章節提到的各種問題,我們可以封裝一個json encode的示例函數:
~~~
function json_encode( data, empty_table_as_object )
--lua的數據類型里面,array和dict是同一個東西。對應到json encode的時候,就會有不同的判斷
--對于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.
--cjson對于空的table,就會被處理為object,也就是{}
--dkjson默認對空table會處理為array,也就是[]
--處理方法:對于cjson,使用encode_empty_table_as_object這個方法。文檔里面沒有,看源碼
--對于dkjson,需要設置meta信息。local a= {};a.s = {};a.b='中文';setmetatable(a.s, { __jsontype = 'object' });ngx.say(comm.json_encode(a))
local json_value = nil
if json.encode_empty_table_as_object then
json.encode_empty_table_as_object(empty_table_as_object or false) -- 空的table默認為array
end
if require("ffi").os ~= "Windows" then
json.encode_sparse_array(true)
end
pcall(function (data) json_value = json.encode(data) end, data)
return json_value
end
~~~
- 序
- Lua簡介
- Lua環境搭建
- 基礎數據類型
- 表達式
- 控制結構
- if/else
- while
- repeat
- 控制結構for的使用
- break,return
- Lua函數
- 函數的定義
- 函數的參數
- 函數的返回值
- 函數回調
- 模塊
- String庫
- Table庫
- 日期時間函數
- 數學庫函數
- 文件操作
- 元表
- 面向對象編程
- FFI
- LuaRestyRedisLibrary
- select+set_keepalive組合操作引起的數據讀寫錯誤
- redis接口的二次封裝(簡化建連、拆連等細節)
- redis接口的二次封裝(發布訂閱)
- pipeline壓縮請求數量
- script壓縮復雜請求
- LuaCjsonLibrary
- json解析的異常捕獲
- 稀疏數組
- 空table編碼為array還是object
- 跨平臺的庫選擇
- PostgresNginxModule
- 調用方式簡介
- 不支持事務
- 超時
- 健康監測
- SQL注入
- LuaNginxModule
- 執行階段概念
- 正確的記錄日志
- 熱裝載代碼
- 阻塞操作
- 緩存
- sleep
- 定時任務
- 禁止某些終端訪問
- 請求返回后繼續執行
- 調試
- 調用其他C函數動態庫
- 我的lua代碼需要調優么
- 變量的共享范圍
- 動態限速
- shared.dict 非隊列性質
- 如何添加自己的lua api
- 正確使用長鏈接
- 如何引用第三方resty庫
- 使用動態DNS來完成HTTP請求
- 緩存失效風暴
- Lua
- 下標從1開始
- 局部變量
- 判斷數組大小
- 非空判斷
- 正則表達式
- 不用標準庫
- 虛變量
- 函數在調用代碼前定義
- 抵制使用module()函數來定義Lua模塊
- 點號與冒號操作符的區別
- 測試
- 單元測試
- API測試
- 性能測試
- 持續集成
- 灰度發布
- web服務
- API的設計
- 數據合法性檢測
- 協議無痛升級
- 代碼規范
- 連接池
- c10k編程
- TIME_WAIT問題
- 與Docker使用的網絡瓶頸
- 火焰圖
- 什么時候使用
- 顯示的是什么
- 如何安裝火焰圖生成工具
- 如何定位問題