webmcp
view framework/env/encode/json.lua @ 51:791849c58105
class_prototype.object:try_save() can create rows with DEFAULT VALUES
| author | jbe | 
|---|---|
| date | Fri Jun 10 14:23:35 2011 +0200 (2011-06-10) | 
| parents | e017c47d43b5 | 
| children | 32ec28229bb5 | 
 line source
     1 --[[--
     2 json_string =  -- JavaScript code representing the given datum (with quotes, if needed)
     3 encode.json(
     4   obj          -- true, false, nil or a number or string
     5 )
     7 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).
     9 TODO: can't distinguish unambiguously between empty object and empty list!
    11 --]]--
    13 -- TODO: check if numeric representations are JSON compatible
    15 function encode.json(obj)
    16   if obj == nil then
    17     return "null";
    18   elseif atom.has_type(obj, atom.boolean) then
    19     return tostring(obj)
    20   elseif atom.has_type(obj, atom.number) then
    21     return tostring(obj)
    22   elseif type(obj) == "table" then
    23     local parts = {}
    24     local first = true
    25     if #obj > 0 then
    26       parts[#parts+1] = "["
    27       for idx, value in ipairs(obj) do
    28         if first then
    29           first = false
    30         else
    31           parts[#parts+1] = ","
    32         end
    33         parts[#parts+1] = tostring(value)
    34       end
    35       parts[#parts+1] = "]"
    36     else
    37       parts[#parts+1] = "{"
    38       for key, value in pairs(obj) do
    39         if first then
    40           first = false
    41         else
    42           parts[#parts+1] = ","
    43         end
    44         parts[#parts+1] = encode.json(key)
    45         parts[#parts+1] = ":"
    46         parts[#parts+1] = encode.json(value)
    47       end
    48       parts[#parts+1] = "}"
    49     end
    50     return table.concat(parts)
    51   else
    52     local str = atom.dump(obj)
    53     str = string.gsub(str, ".",
    54       function (char)
    55         if char == '\r' then return '\\r'  end
    56         if char == '\n' then return '\\n'  end
    57         if char == '\\' then return '\\\\' end
    58         if char == '"'  then return '\\"'  end
    59         local byte = string.byte(char)
    60         if byte < 32 then return string.format("\\u%04x", byte) end
    61       end
    62     )
    63     str = string.gsub(str, "</", "<\\/")
    64     str = string.gsub(str, "<!%[CDATA%[", "\\u003c![CDATA[")
    65     str = string.gsub(str, "]]>", "]]\\u003e")
    66     return '"' .. str .. '"'
    67   end
    68 end
