jQuery.parseJSON single quote vs double quote

JavascriptJqueryJson

Javascript Problem Overview


What actually the difference between this?

This works fine:

var obj1 = jQuery.parseJSON('{"orderedList": "true"}');
document.write("obj1 "+ obj1.orderedList );

but the following does not work:

var obj2 = jQuery.parseJSON("{'orderedList': 'true'}");
document.write("obj2 "+ obj2.orderedList );

Why is that?

Javascript Solutions


Solution 1 - Javascript

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 https://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response

Solution 2 - Javascript

As per the API documentation, double quotes are considered valid JSON, single quotes aren't.

http://api.jquery.com/jQuery.parseJSON/

Solution 3 - Javascript

Go to www.Jsonlint.com website and check your single quotes json string you will found that it is not a valid json string. Because double quotes json is standard json format.

jsonlint.com is a website to check json format right or not.

Solution 4 - Javascript

You could use replace to fix this. This worked for me.

var str = "{'orderedList': 'true'}";

str = str.replace(/\'/g, '\"');

JSON.parse(str);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsadaf2605View Question on Stackoverflow
Solution 1 - Javascriptch4nd4nView Answer on Stackoverflow
Solution 2 - JavascriptDavid MView Answer on Stackoverflow
Solution 3 - JavascriptParveen VermaView Answer on Stackoverflow
Solution 4 - JavascriptMacfer AnnView Answer on Stackoverflow