webmcp
diff framework/env/encode/json.lua @ 10:e017c47d43b5
Modified encode.json to avoid special CDATA sequences in output
author | jbe |
---|---|
date | Wed Feb 03 00:57:18 2010 +0100 (2010-02-03) |
parents | 985024b16520 |
children | 32ec28229bb5 |
line diff
1.1 --- a/framework/env/encode/json.lua Sun Jan 31 18:37:38 2010 +0100 1.2 +++ b/framework/env/encode/json.lua Wed Feb 03 00:57:18 2010 +0100 1.3 @@ -4,7 +4,8 @@ 1.4 obj -- true, false, nil or a number or string 1.5 ) 1.6 1.7 -This function encodes any native datatype or atom in JavaScript object notation (JSON). 1.8 +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). 1.9 + 1.10 TODO: can't distinguish unambiguously between empty object and empty list! 1.11 1.12 --]]-- 1.13 @@ -48,19 +49,20 @@ 1.14 end 1.15 return table.concat(parts) 1.16 else 1.17 - return 1.18 - '"' .. 1.19 - string.gsub(atom.dump(obj), ".", 1.20 - function (char) 1.21 - if char == '\r' then return '\\r' end 1.22 - if char == '\n' then return '\\n' end 1.23 - if char == '\\' then return '\\\\' end 1.24 - if char == '"' then return '\\"' end 1.25 - if char == '/' then return '\\/' end -- allowed according to RFC4627, needed for </script> 1.26 - local byte = string.byte(char) 1.27 - if byte < 32 then return string.format("\\u%04x", byte) end 1.28 - end 1.29 - ) .. 1.30 - '"' 1.31 + local str = atom.dump(obj) 1.32 + str = string.gsub(str, ".", 1.33 + function (char) 1.34 + if char == '\r' then return '\\r' end 1.35 + if char == '\n' then return '\\n' end 1.36 + if char == '\\' then return '\\\\' end 1.37 + if char == '"' then return '\\"' end 1.38 + local byte = string.byte(char) 1.39 + if byte < 32 then return string.format("\\u%04x", byte) end 1.40 + end 1.41 + ) 1.42 + str = string.gsub(str, "</", "<\\/") 1.43 + str = string.gsub(str, "<!%[CDATA%[", "\\u003c![CDATA[") 1.44 + str = string.gsub(str, "]]>", "]]\\u003e") 1.45 + return '"' .. str .. '"' 1.46 end 1.47 end