Jquery.Parsejson Throws "Invalid JSON" Error Due to Escaped Single Quote in JSON

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:

http://www.json.org/string.gif



Update - More information for those that are interested:


Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:

JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.

So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.



Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:

The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

...

  • Strings may be quoted with ' (single quote).

This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:

public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {

...

case '\\':
c = this.next();
switch (c) {

...

case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...

At the top of the method is an informative comment:

The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.

So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.


Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:

parseJSON: function( data ) {
...

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

...

jQuery.error( "Invalid JSON: " + data );
},

As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.

unable to parse json data that includes a single quote

Looks like you are doing double serialisation on the server side. Happens for example if your web framework automatically serialises the returned object but you make an extra explicit, unnecessary serialise call on your object. The fact that your code works with no ' cases proves this: jquery makes one parse automatically (because of the dataType) then you run another parseJSON. That shouldn't work :)
Fix your serialisation on the server side and remove the unnecessary parseJSON call from your success method. Every other solution is just a workaround not a real fix.

JSON string containing escaped single quote flagged as invalid

You don't need to escape a ' with a backslash. Just escape the ".

jQuery.parseJSON single quote vs double quote

That's because double quotes is considered standard while single quote is not. This is not really specific to JQuery, but its about JSON standard. So irrespective of JS toolkit, you should expect same behaviour.

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Update

Or perhaps its a duplicate of jQuery single quote in JSON response

Why is this JSON String invalid? jQuery.parseJSON function throws invalid character

The error is because the $.post method has already detected a JSON response and parsed the result to an object for you. You are then trying to call parseJSON on an object instead of a JSON string, which results in the error you've seen. You simply need to remove the call to $.parseJSON. Try this:

function updateProgrammerDetails(site, Id) {
$.post('EngineAdminServlet', {
action: "updateProgrammerMenu",
siteDetails: site,
ID: Id,
}, function(data, status) {
var pid, name, sky, ip, eleven;
// work with the object in 'data' here, E.g:
console.log(data.ID, data.siteName); // = 123, 'VEGAS'
}).fail(function(error) {
alert("Error retrieving details from server");
}); //end ajax call
}

jQuery.parseJSON() Invalid Character error

First: you already have a JSON object here, jQuery.parseJSON() takes a string as input.

Second: to access data[i] properties you'll also have to pass a list of objects.

So:

var data = $.parseJSON('[{"senderEmail": "Email@gmail.com", "ReceiverEmail": "alll", "Message": "j", "DateAndTime": "2013"}]');

for (var i = 0; i < data.length; i++) {
// Now you can access data[i] properties as you want...
}


Related Topics



Leave a reply



Submit