jQuery makes it extremely easy to deal with JSON data. In the below example server sends a success message to browser. The JSON data looks like this.
The jQuery code to handle JSON data looks like this.
It all looks good and the code works with jQuery 1.3 .
However if you upgrade to jQuery 1.4 then above code will stop working. Why? jQuery 1.4 does strict JSON parsing using native parse method and any malformed JSON structure will be rejected.
How jQuery 1.3 parses JSON structure
You will get a valid output.
JSON specification says that all string values must use double quotes. Single quotes are not allowed. What it means is that following JSON structures are not valid JSON.
However they will not work if you upgrade to jQuery 1.4 .
jQuery 1.4 uses native JSON parsing
As you can see a string which was successfully parsed by
eval failed by
window.JSON.parse . It might or might not fail in chrome. More on that later. Since jQuery 1.4 will rely on browsers parsing the JSON structure malformed JSON structures will fail.
In order to ensure that JSON is correctly parsed by the browsers, jQuery does some code cleanup to make sure that you are not trying to pass something malicious. You will not be able to test this thing directly using firebug but if you make an AJAX request and from server if you send response the you can verify the following code.
Following JSON structure will be correctly parsed in jQuery 1.3 . However the same JSON structure will fail in jQuery 1.4 . Why? Because of dangling open bracket
jQuery 1.4 has following code that does some data cleanup to get around the security issue with JSON parsing before sending that data to browser for parsing. Here is a snippet of the code.
Not all browsers parse JSON same way
Earlier I mentioned that following JSON structure will not be correctly parsed by browsers.
All browsers will fail to parse above JSON structure except
chrome . Look at this blog titled Cross Browser JSON parsing to get more insight into this issue.
I have malformed JSON and I want to use jQuery 1.4
If you have malformed JSON and you want to use jQuery 1.4 then you should send the datatype as
text and then convert the returned JSON structure using eval. Here is one way you can do that.
jQuery attempts to parse JSON natively. However if native JSON parsing is not available then it falls back to
eval. Here by setting
window.JSON to null browser is faking that it does not have support for native JSON parsing.
Use JSONLint if you want to play with various strings to see which one is valid JSON and which one is not.