const val1 = "{a: '123'}";
console.log(typeof(val1)); // string
const a = JSON.parse(val1); // Gives Error:
This happens because val1
here is not a valid json string, as property a
and its value inside the object is not wrapped in double quotes. After doing that you can see it works fine:
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
b.a
is undefined
here because b
is not actually an object here but 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 happens because
JSON.stringify(val1)
converts "{a: '123'}"
to ""{a: '123'}""
. It simply add double quotes around val1
as it was already a string.
and using JSON.parse
on it just removed the double quotes from it and we got back string again.
const val1 = "{a: '123'}";
const val2 = JSON.stringify(val1);
console.log( val2 ) // "{a: '123'}" ... its actually ""{a: '123'}""
console.log( typeof val2 ) // string
const val3 = JSON.parse(val2);
console.log( val3 ) // {a: '123'} ... its actually "{a: '123'}"
console.log( typeof val3 ) // string