76

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
sadaf2605
  • 7,332
  • 8
  • 60
  • 103
  • Few related posts [here](https://stackoverflow.com/q/242813/465053) and [here](https://stackoverflow.com/q/2275359/465053). – RBT Sep 15 '17 at 05:50

4 Answers4

107

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

Community
  • 1
  • 1
ch4nd4n
  • 4,110
  • 2
  • 21
  • 43
25

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

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

David M
  • 71,481
  • 13
  • 158
  • 186
  • 1
    I vouch for this answer. But one question remains: why double quotes? I can only assume they picked double quotes because it's more common in programming languages to use double quotes for strings. In some languages single quotes are used for single-byte characters, *not* for strings. – Tim S. Jan 16 '13 at 10:05
  • 3
    @Tim - see Ck's answer below... Also, note that within a string, you're more likely to use an apostrophe/single quote than a double one, so double quotes to delimit strings is likely to be easier to work with. – David M Jan 16 '13 at 10:06
  • 2
    The reasons behind https://tools.ietf.org/html/rfc4627 I don't know. But that RFC is the reason why jQuery picked double quotes. – user625488 Feb 09 '16 at 17:28
4

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.

Purush Pawar
  • 4,263
  • 2
  • 29
  • 37
Parveen Verma
  • 16,690
  • 1
  • 14
  • 19
2

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

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

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

JSON.parse(str);
eebbesen
  • 5,070
  • 8
  • 48
  • 70
Macfer Ann
  • 153
  • 1
  • 9