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.
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.
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.
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.
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.
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 .
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"}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With