user310291 user310291 - 3 months ago 9
JSON Question

Why can't I use ' instead of " for JSON string?

I have a very basic json string, to my surprise I got this error :


Json unexpected token at position 1


https://jsfiddle.net/5L2sgr57/

var jsonString = "{'name': 'john'}";
JSON.parse(jsonString);


It works if I switch ' with " but for what reason would I need to do so since in javascript string ' and " are supposedly equivalent ?

Answer

Switch your single and double quotation marks

var jsonString = '{"name": "john"}';
JSON.parse(jsonString);

JSON is not equal to Javascript

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. (www.json.org)

You can verify the allowed JSON syntax here

In the syntax-definition for a string, you can see that 'is not allowed.

enter image description here

Comments