Niels Sandholt Busch RSS

Danish software developer based in Copenhagen.

Archive

Dec
23rd
Fri
permalink
Nov
6th
Sun
permalink
Aug
27th
Sat
permalink
Jul
9th
Sat
permalink
Dec
25th
Sat
permalink

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… | Comment »

Oct
7th
Thu
permalink
Sep
23rd
Thu
permalink
Jul
14th
Wed
permalink
Jul
3rd
Sat
permalink
Jun
27th
Sun
permalink