JavaScript - why does JSON.parse(['123']) return 123?
Can you help me to understand the behavior of JSON.parse()
?
It should work for only strings but seems to work for an array that contains only one string if the string contains only numbers.
xxxxxxxxxx
JSON.parse(['123']); // 123
JSON.parse(['123abc']); // throws SyntaxError
JSON.parse(['123', '123']); // throws SyntaxError
JSON.parse()
expects a string and not an array.
However, when we pass an array or any other non-string value, the method automatically converts it to a string and continues instead of throwing an error immediately.
The string representation of an array consists of its values separated by commas:
xxxxxxxxxx
console.log(String(['123'])); // '123'
console.log(String(['123abc'])); // '123abc'
console.log(String(['123', '123'])); // '123,123'
Notice that ['123']
and [123]
both convert to the same string: '123'
.
So what you're doing is basically:
xxxxxxxxxx
JSON.parse('123');
JSON.parse('123abc');
JSON.parse('123,123');
The last two are not valid JSON, so JSON.parse()
throws an error in both cases.
The first one - 123
is a Number literal and therefore valid JSON, representing itself.
That's why JSON.parse('123')
(and by extension JSON.parse(['123']))
returns the numeric value 123
.