Languages

JavaScript - why does JSON.parse(['123']) return 123?

0 points
Asked by:
Anisha-Kidd
652

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.

1 answer
0 points
Answered by:
Admin Dirask Community
4380

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:

Notice that ['123'] and [123] both convert to the same string: '123'.

So what you're doing is basically:

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.

 

References

  1. JSON.parse() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join