webmcp
view framework/env/encode/json.lua @ 0:9fdfb27f8e67
Version 1.0.0
| author | jbe/bsw | 
|---|---|
| date | Sun Oct 25 12:00:00 2009 +0100 (2009-10-25) | 
| parents | |
| children | 985024b16520 | 
 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).
     9 --]]--
    11 function encode.json(obj)
    12   if obj == nil then
    13     return "null";
    14   elseif atom.has_type(obj, atom.boolean) then
    15     return tostring(obj)
    16   elseif atom.has_type(obj, atom.number) then
    17     return tostring(obj)
    18   else
    19     return
    20       "'" ..
    21       string.gsub(atom.dump(obj), ".",
    22         function (char)
    23           if char == "\r" then return "\\r"  end
    24           if char == "\n" then return "\\n"  end
    25           if char == "\\" then return "\\\\" end
    26           if char == "'"  then return "\\'"  end
    27           if char == "/"  then return "\\/"  end  -- allowed according to RFC4627, needed for </script>
    28           local byte = string.byte(char)
    29           if byte < 32 then return string.format("\\u%04x", byte) end
    30         end
    31       ) ..
    32       "'"
    33   end
    34 end
