lua-cjson icon indicating copy to clipboard operation
lua-cjson copied to clipboard

cjson.encode() modified order

Open yhc19850706 opened this issue 5 years ago • 7 comments

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?

yhc19850706 avatar Nov 09 '20 06:11 yhc19850706

Hi,

same problem here, any lead ?

Thanks.

dannygueta avatar Mar 01 '21 21:03 dannygueta

I hava the same problem,anybody knows why?

libing0526 avatar Sep 10 '21 03:09 libing0526

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.

doujiang24 avatar Sep 10 '21 05:09 doujiang24

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.

travisbell avatar Sep 10 '21 14:09 travisbell

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.

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

libing0526 avatar Sep 13 '21 09:09 libing0526

https://plain.blog.csdn.net/article/details/120364853 it seems like a good method

libing0526 avatar Sep 24 '21 08:09 libing0526

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"}

edo888 avatar Apr 16 '22 15:04 edo888