webmcp

view framework/env/encode/json.lua @ 7:f7413a1a872c

Tags for v1.0.0 to v1.0.6 added
author jbe
date Sat Jan 30 12:41:37 2010 +0100 (2010-01-30)
parents 985024b16520
children e017c47d43b5
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).
8 TODO: can't distinguish unambiguously between empty object and empty list!
10 --]]--
12 -- TODO: check if numeric representations are JSON compatible
14 function encode.json(obj)
15 if obj == nil then
16 return "null";
17 elseif atom.has_type(obj, atom.boolean) then
18 return tostring(obj)
19 elseif atom.has_type(obj, atom.number) then
20 return tostring(obj)
21 elseif type(obj) == "table" then
22 local parts = {}
23 local first = true
24 if #obj > 0 then
25 parts[#parts+1] = "["
26 for idx, value in ipairs(obj) do
27 if first then
28 first = false
29 else
30 parts[#parts+1] = ","
31 end
32 parts[#parts+1] = tostring(value)
33 end
34 parts[#parts+1] = "]"
35 else
36 parts[#parts+1] = "{"
37 for key, value in pairs(obj) do
38 if first then
39 first = false
40 else
41 parts[#parts+1] = ","
42 end
43 parts[#parts+1] = encode.json(key)
44 parts[#parts+1] = ":"
45 parts[#parts+1] = encode.json(value)
46 end
47 parts[#parts+1] = "}"
48 end
49 return table.concat(parts)
50 else
51 return
52 '"' ..
53 string.gsub(atom.dump(obj), ".",
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 if char == '/' then return '\\/' end -- allowed according to RFC4627, needed for </script>
60 local byte = string.byte(char)
61 if byte < 32 then return string.format("\\u%04x", byte) end
62 end
63 ) ..
64 '"'
65 end
66 end

Impressum / About Us