Reputation: 1885
This question is about
why the outputs are different
not how can i achieve the proper output.
I am unable to understand why the output of following two scenarios is not the same, even if I am giving the same argument to the JSON.parse() function.
FIRST scenario
obj = {a:"asdf"};
var newObj = JSON.parse(JSON.stringify(obj)); //newObj = {a:"asdf"}
SECOND scenario
var newObj = JSON.parse("{"a":"asdf"}"); //this gives an error
Upvotes: 1
Views: 307
Reputation: 4819
why the outputs are different
Because the inputs are different.
FIRST scenario
obj = {a:"asdf"};
var newObj = JSON.parse(JSON.stringify(obj));
Here the input parameter of JSON.parse
is JSON.stringify(obj)
and this is a string that reads {"a":"asdf"}
.
SECOND scenario
var newObj = JSON.parse("{"a":"asdf"}");
Here the input parameter of JSON.parse
is a string that reads {
and the rest is broken code.
Confusion arises because the console debugger decides all strings should be shown on the console encapsulated with a "
, but this is just a way for the console to tell you that this value is of type String. It does not check whether you have " inside and escape them.
The encapsulating "
are not part of the string, only a way of telling it is a string.
If console.logging JSON.stringify(obj) gets you "{"a":"asdf"}"
try doing alert instead, or document.write. These will not add extra "
and you will see that the value of JSON.stringify(obj) is actually {"a":"asdf"}
, not "{"a":"asdf"}"
.
<html><head></head><body>
<script>
function JSONparse(string) {
document.write(string);
alert(string);
console.log(string);
return JSON.parse(string);
}
var obj = {a:"asdf"};
result = JSONparse(JSON.stringify(obj));
</script>
</body></html>
Upvotes: 1
Reputation: 4397
The problem is with quotes.
var newObj = JSON.parse('{"a":"asdf"}');
should work correctly.
In Javascript, we use quotes (single or double) to represent a String. When you want to define a String that contains quotes, then you must use different quotes, or escape
the quotes using backslash \
character.
var newObj = JSON.parse("{\"a\":\"asdf\"}");
also works fine.
You might think that
var newObj = JSON.parse("{'a':'asdf'}");
would work, but no. In JSON, strings are defined using Double quotes only.
Upvotes: 3