How to properly escape user-controlled input when it's inserted as a value in JSON object?
<script>
$(document).ready(function() {
new MyObject({
key1: "user_input",
key2: ["user_input1", "user_input2"]
});
});
</script>
How to properly escape user-controlled input when it's inserted as a value in JSON object?
<script>
$(document).ready(function() {
new MyObject({
key1: "user_input",
key2: ["user_input1", "user_input2"]
});
});
</script>
http://code.google.com/p/json-sanitizer/ takes JSON-like content and converts it to JSON that is safe to evaluate as JavaScript source code and which can be embedded in HTML <script>
elements and in XML <![CDATA[...]]>
sections.
For example, given
{
key1: "user_input",
key2: ["user_input1", "user_input2"]
}
It preserves several properties:
\u....
escaped."
), backslashes (\
) are \u....
escaped to ensure that strings do not end prematurely.<
and >
) are \u....
escaped as necessary to prevent strings from containing the literal text </script
or ]]>
which would prevent embedding.\u....
escaped including U+0-U+1F excluding tab, U+7F, U+FFFE, U+FFFF.\u....
escaped.\012
), two-digit hex escaped (\x0A
), and single character escapes (\!
).It can be a good idea to \u....
escape things like +
to defang UTF-7.
/
as \/
which will defang </script>
close tags.
Nov 1, 2012 at 18:41