X-Git-Url: https://git.enpas.org/?a=blobdiff_plain;f=util%2Fjson.lua;h=efc602f0ed7a183b064b5be7307e018c8977a212;hb=a0dc04ad05a5a436c967383e9ba06d5cc11e2e88;hp=05453703369e35f642b11acd61c33f93c5e2a97e;hpb=c6ba514283042545c66e20f12e844c1372a54d4c;p=prosody.git diff --git a/util/json.lua b/util/json.lua index 05453703..efc602f0 100644 --- a/util/json.lua +++ b/util/json.lua @@ -1,6 +1,6 @@ local type = type; -local t_insert, t_concat, t_remove = table.insert, table.concat, table.remove; +local t_insert, t_concat, t_remove, t_sort = table.insert, table.concat, table.remove, table.sort; local s_char = string.char; local tostring, tonumber = tostring, tonumber; local pairs, ipairs = pairs, ipairs; @@ -79,11 +79,25 @@ function tablesave(o, buffer) if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then t_insert(buffer, "{"); local mark = #buffer; - for k,v in pairs(hash) do - stringsave(k, buffer); - t_insert(buffer, ":"); - simplesave(v, buffer); - t_insert(buffer, ","); + if buffer.ordered then + local keys = {}; + for k in pairs(hash) do + t_insert(keys, k); + end + t_sort(keys); + for _,k in ipairs(keys) do + stringsave(k, buffer); + t_insert(buffer, ":"); + simplesave(hash[k], buffer); + t_insert(buffer, ","); + end + else + for k,v in pairs(hash) do + stringsave(k, buffer); + t_insert(buffer, ":"); + simplesave(v, buffer); + t_insert(buffer, ","); + end end if next(__hash) ~= nil then t_insert(buffer, "\"__hash\":["); @@ -129,17 +143,24 @@ function json.encode(obj) simplesave(obj, t); return t_concat(t); end +function json.encode_ordered(obj) + local t = { ordered = true }; + simplesave(obj, t); + return t_concat(t); +end ----------------------------------- function json.decode(json) + json = json.." "; -- appending a space ensures valid json wouldn't touch EOF local pos = 1; local current = {}; local stack = {}; local ch, peek; local function next() ch = json:sub(pos, pos); + if ch == "" then error("Unexpected EOF"); end pos = pos+1; peek = json:sub(pos, pos); return ch; @@ -166,7 +187,7 @@ function json.decode(json) skipwhitespace(); if ch == "/" and peek == "*" then skipstarcomment(); - elseif ch == "/" and peek == "*" then + elseif ch == "/" and peek == "/" then skiplinecomment(); else return;