Languages

JavaScript - why is number literal a valid JSON to parse and string is not?

0 points
Asked by:
JoanneSenior
1070

Why is number literal a valid JSON to use in JSON.parse() method and string is not?

For example, I can parse '123' but '123abc' throws a SyntaxError and I'm not sure why.

My code:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

JSON.parse() method expects a string but it doesn't wrap the argument inside the string with additional quotation marks.

In short, you can JSON.parse() everything you can assign to a variable.

Trying to JSON.parse('123abc') is like you were trying to assign a string to a variable like that:

It needs to be wrapped with quotation marks to be a valid code:

The same goes for the argument of the JSON.parse() method:

 

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