const val1 = "{a: '123'}";
console.log(typeof(val1)); // string
const a = JSON.parse(val1); // Gives Error:
This issue arises because the variable val1
is not a valid JSON string, as the property a
and its value inside the object are not enclosed in double quotes. Once we correct this, it works as expected:
const val1 = '{"a": "123"}';
console.log(typeof(val1)); // string
const a = JSON.parse(val1); // It works!
console.log(a)
const b = JSON.parse(JSON.stringify(val1));
console.log(b); // {a: '123'}
console.log(b.a); // ---> undefined
The reason why b.a
is undefined here is that b
is not actually an object but a string:
const val1 = "{a: '123'}";
const b = JSON.parse(JSON.stringify(val1));
console.log(b); // {a: '123'}
console.log(typeof b); // string
console.log(b.a); // ---> undefined
This behavior occurs because
JSON.stringify(val1)
converts "{a: '123'}"
to ""{a: '123'}""
, adding extra double quotes around
val1</code which was already a string.</p>
<p>By applying <code>JSON.parse
to it, the double quotes are removed, resulting in the original string again.
const val1 = "{a: '123'}";
const val2 = JSON.stringify(val1);
console.log( val2 ) // "{a: '123'}" ... it's actually ""{a: '123'}""
console.log( typeof val2 ) // string
const val3 = JSON.parse(val2);
console.log( val3 ) // {a: '123'} ... it's actually "{a: '123'}"
console.log( typeof val3 ) // string