sniper00 / moon

A lightweight game server framework implemented with Actor Model
MIT License
721 stars 158 forks source link

lua-json添加选项: 数组是稀疏数组时, encode table为 json object #163

Closed sniper00 closed 9 months ago

sniper00 commented 9 months ago

编写逻辑时很容易用到table key1起始的lua table, 如果写出下面代码

json.options('enable_sparse_array', true)
local t = {}
t[1] = "111"
t[2] = "222"
t[3] = "333"
t[4] = "444"

t[3] = nil

local str = json.encode(t)
print(str)
print_r(json.decode(str))

对于 json 中的 null 会使用 json.null lua lightuserdata 表示:

encode:   ["111","222",null,"444"] 
decode:   {
    [1] = "111",
    [2] = "222",
    [3] = userdata: 0000000000000000,
    [4] = "444",
}

这样在编写lua逻辑时判断元素是否存在时会比较麻烦,需要多一层对json.null的判断。 对于lua 大多数情况下并不关系数据是array还是object, 为了简化,现在提供了选项 json options enable_sparse_array , 这个选项是默认为false。效果如下:

encode:   {"1":"111","2":"222","4":"444"}
decode:   {
    [1] = "111",
    [2] = "222",
    [4] = "444",
}

注意,如果要对接其它语言,需要区分arrayobject时, 按object操作方式的table 不建议定义 key=1的元素