cjson.encode() modified order
when i use cjson.encode(table), the table is modified order ,why? e.g: local json = cjson.encode({name="yhc",age=40,birthday="1985"})
print(json) -- {"birthday":"1985","name":"yhc","age":40}
i don't want to change,how to do?
Hi,
same problem here, any lead ?
Thanks.
I hava the same problem,anybody knows why?
cjson.encode can not have the fixed order since Lua table doesn't have a fixed order for keys.
otherwise, cjson.encode have to sort for the keys, it will hit bad performance then.
There is a PR on the original mpx/lua-cjson repo here, that adds support for this. It only took a few small tweaks to get working with the latest openresty/lua-cjson. I have a working branch of this here.
Just configure OpenResty with the --without-lua_cjson flag, and then you can just build and require your own custom cjson (I'm using LuaRocks for this) in your project. I've been using this in production for almost a year with no problems. Performance is still great.
There is a PR on the original mpx/lua-cjson repo here, that adds support for this. It only took a few small tweaks to get working with the latest openresty/lua-cjson. I have a working branch of this here.
Just configure OpenResty with the
--without-lua_cjsonflag, and then you can just build and require your own custom cjson (I'm using LuaRocks for this) in your project. I've been using this in production for almost a year with no problems. Performance is still great.
This is a good method, but it seems that it can only be applied to a small amount of data. The number of citations Lua stack is limited to 20
https://plain.blog.csdn.net/article/details/120364853 it seems like a good method
You can possibly define the order you want in __order metatable and use the forked version: https://github.com/edo888/lua-cjson
local cjson = require "cjson.safe"
cjson.decode_save_key_order(true)
local json = {name="yhc",age=40,birthday="1985"}
setmetatable(json, {
__order = {"name", "age", "birthday"}
})
print(cjson.encode(json))
Output:
{"name":"yhc","age":40,"birthday":"1985"}