EN
JavaScript - why is number literal a valid JSON to parse and string is not?
1 answers
0 points
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:
xxxxxxxxxx
1
JSON.parse('123');
2
3
JSON.parse('123abc'); // throws SyntaxError
1 answer
0 points
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:
xxxxxxxxxx
1
const x = 123abc;
It needs to be wrapped with quotation marks to be a valid code:
xxxxxxxxxx
1
const x = "123abc";
The same goes for the argument of the JSON.parse()
method:
xxxxxxxxxx
1
JSON.parse('123');
2
3
JSON.parse('"123abc"');
References
0 commentsShow commentsAdd comment