Ankur Marwaha Ankur Marwaha - 29 days ago 6
Javascript Question

Different behaviour of json.parse for same input?

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"}


Debugging
Debugging view

SECOND scenario

var newObj = JSON.parse("{"a":"asdf"}"); //this gives an error

Answer

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>
Comments