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

What is the sorting basis for key values after `decode`?

Open NoWait126 opened this issue 2 years ago • 1 comments

Here is the content of json file

{
    "1": "1",
    "2": "2",
    "3": "3",
    "4": "4"
}

here is my code

local cjson = require "cjson"
local function load_file(user_conf_file)
    local f = io.open(user_conf_file)
    if not f then
      return nil
    end
    local cont = f:read("*a")
    f:close()
    local fjson = cjson.decode(cont)
    for k, v in pairs(fjson) do
      print(k)
    end
    return true
end

The output order is different each time,such as1432, 3142 . So what is the sorting basis for key values after decode? Is there a way to guarantee the original order?

NoWait126 avatar Aug 19 '23 01:08 NoWait126

luajit adds randomness to lua table, so the order in which the table is traversed is not fixed.

zhuizhuhaomeng avatar Aug 19 '23 08:08 zhuizhuhaomeng