Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Object With or Without Quotes

I am trying to learn JSON, i learned that any javascript object with the key in double quotes are considered as JSON object.

And i constructed this object

var jstr1 = {"mykey": "my value"};

But when i try to parse using JSON.parse(jstr1), i got the following error. see the screenshot.

enter image description here

But when i try to parse this

var jstr = '{"mykey": "my value"}';,

i got the success, see the screenshot. i got confused with this. Please explain me why this happens. what is the difference between the two forms.

And when i got JSON as a response from any services, how it would look like, whether it will be in form of jstr or jstr1

thanks in advance for any help.

like image 603
Mohamed Hussain Avatar asked Sep 05 '13 11:09

Mohamed Hussain


People also ask

Are quotes necessary in JSON?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.

Do JSON field names need quotes?

Properties in JSON have to be strings, and in JSON as string is defined as "a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes". In other words using single quotes, or no quotes at all is not allowed.

Does JSON need single or double quotes?

JSON only allows double quotes (unless you control the data, and can use a library that is more liberal at parsing JSON - but a JSON file with single quotes is not truly a JSON file) Most likely noobies to JS will be familiar with double quotes from their previous programming languages.

Can JSON object use single quotes?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .


1 Answers

You are creating a Javascript Object. If you want a JSON-string from it, use JSON.stringify.

So

var myObj = {mykey: "my value"}
   ,myObjJSON = JSON.stringify(myObj);

Based on comments: There is no such thing as a JSON Object. There are JSON-strings, which can be parsed to Javascript Objects. Javascript Objects can be stringified to JSON strings. Within a JSON-string keys and values are quoted. So the result of the above is a string containing '{"mykey":"my value"}'.

Try parsing myObjJSON in your browser console (using: JSON.parse(myObjJSON)) and you get: Object {mykey: "my value"}.

like image 149
KooiInc Avatar answered Nov 11 '22 18:11

KooiInc