Just like XML, JSON data need to be parsed to be utilized in software. The two major locations within a Web application architecture where JSON needs to be parsed are in the browser of the client and in application code on the server.
From http://www.json.org/js.html :
var myObject = eval(‘(‘ + myJSONtext + ‘)’);
So the essential question is: How can programmers and applications parse untrusted JSON safely?
Parsing JSON safely, Client Side
Parsing JSON in the browser is often the result of an asynchronous request returning JSON to the browser. Another technique that is becoming more common is to embed JSON directly in a Web page server side, and then to parse and render that JSON on the client side. The mechanism of embedding JSON safely in a Web page is described here: https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233.1_-_HTML_escape_JSON_values_in_an_HTML_context_and_read_the_data_with_JSON.parse
In this description, Step 1 shows safely embedded JSON on a Web page through HTML Entity Encoding:
<span style=”display:none” id=”init_data”>
<%= data.to_json %> <– data is HTML escaped –>
Steps 2 and 3 includes decoding the JSON data and then parsing it safely:
// unescapes the content of the span
var jsonText = document.getElementById(‘init_data’).innerHTML;
// parse untrusted JSON safely
var initData = JSON.parse(jsonText);
Parsing JSON safely, Server Side
It’s important to use a formal JSON parser when handling untrusted JSON on the server side. For example, the Java Programing language can utilize the OWASP JSON Sanitizer for Java. The OWASP JSON Sanitizer project aspires to accomplish the following goals:
“Given JSON-like content, converts it to valid JSON.
This can be attached at either end of a data-pipeline to help satisfy Postel’s principle:
Be conservative in what you do; be liberal in what you accept from others.
Applied to JSON-like content from others, the OWASP JSON Sanitizer will produce well-formed JSON that should satisfy any parser you use.
Applied to your own output before you send, it will coerce minor mistakes in encoding and make it easier to embed your JSON in HTML and XML.”
The OWASP JSON Sanitizer project was created and is maintained by Mike Samuel, an esteemed member of the Google Application Security Team. For more information on the OWASP JSON Sanitizer, please visit the OWASP JSON Sanitizer Google Code page.
I hope this article helps you develop safer parsing of JSON in your applications. Please drop me a line if you have any questions at email@example.com.