lørdag den 25. december 2010

How to (safely) embed JSON in a script tag

If you embed JSON in a web page, you must make sure you are not vulnerable to XSS (Cross-site scripting) attacks. Usually you would just HTML escape your content, but that corrupts your JSON.

instead escape the script start and end characters and the ampersand character with their unicode encodings. This will prevent XSS but still allow for valid JSON

json += json.replace('&', '\\u0026') json += json.replace('<', '\\u003c') json += json.replace('>', '\\u003e')

If you use simplejson for generating JSON, the newest version has a JSONEncoderForHTML that does exactly this.

 

Posted via email from Yet another blog...