# HG changeset patch # User jbe # Date 1426986589 -3600 # Node ID aacddd07e471dd6fb79991339bcd38643f508fec # Parent 851452af0c3661e8bf1335af736404e3865abda3 encode.json{...} does not support atoms anymore but uses the JSON library diff -r 851452af0c36 -r aacddd07e471 framework/env/encode/json.lua --- a/framework/env/encode/json.lua Sun Mar 22 01:45:51 2015 +0100 +++ b/framework/env/encode/json.lua Sun Mar 22 02:09:49 2015 +0100 @@ -1,70 +1,19 @@ --[[-- -json_string = -- JavaScript code representing the given datum (with quotes, if needed) +json_string = -- JavaScript code encode.json( - obj -- true, false, nil or a number or string + value -- nil, false, true, a number, a string, or json.array{...} or json.object{...} ) -This function encodes any native datatype or atom in JavaScript object notation (JSON). It ensures that the returned string can be safely included in inline scripts both in HTML and XHTML (within CDATA section). +This function encodes any native datatype or table structure to JavaScript object notation (JSON). In order to distinguish between the empty array and the empty object, use json.array{} and json.object{} respectively. -TODO: can't distinguish unambiguously between empty object and empty list! - -TODO: replace with JSON library +The return value of this function is additionally escaped in such way that it can be safely included in inline scripts both in HTML and XHTML (within CDATA section). --]]-- --- TODO: check if numeric representations are JSON compatible - function encode.json(obj) - if obj == nil then - return "null"; - elseif atom.has_type(obj, atom.boolean) then - return tostring(obj) - elseif atom.has_type(obj, atom.number) then - return tostring(obj) - elseif type(obj) == "table" then - local parts = {} - local first = true - if #obj > 0 then - parts[#parts+1] = "[" - for idx, value in ipairs(obj) do - if first then - first = false - else - parts[#parts+1] = "," - end - parts[#parts+1] = tostring(value) - end - parts[#parts+1] = "]" - else - parts[#parts+1] = "{" - for key, value in pairs(obj) do - if first then - first = false - else - parts[#parts+1] = "," - end - parts[#parts+1] = encode.json(key) - parts[#parts+1] = ":" - parts[#parts+1] = encode.json(value) - end - parts[#parts+1] = "}" - end - return table.concat(parts) - else - local str = atom.dump(obj) - str = string.gsub(str, ".", - function (char) - if char == '\r' then return '\\r' end - if char == '\n' then return '\\n' end - if char == '\\' then return '\\\\' end - if char == '"' then return '\\"' end - local byte = string.byte(char) - if byte < 32 then return string.format("\\u%04x", byte) end - end - ) - str = string.gsub(str, "", "]]\\u003e") - return '"' .. str .. '"' - end + str = json.export(obj) + str = string.gsub(str, "", "]]\\u003e") + return str end