Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.parse work on 1 element arrays?

The documentation seems to say that JSON.parse should only work on strings:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

However, it appears that it works on 1-length array integer values:

-> JSON.parse([123])
<- 123
-> JSON.parse(["[123]"])
<- [123]

However, if there's more than one value, it breaks:

-> JSON.parse([123, 456])
<- VM439:1 Uncaught SyntaxError: Unexpected token , in JSON at position 3
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

Or a single string value:

-> JSON.parse(['string'])
<- VM586:1 Uncaught SyntaxError: Unexpected token s in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

Does anyone know why it behaves this way?

like image 996
Ecksters Avatar asked Feb 02 '26 03:02

Ecksters


1 Answers

Because the param is likely being coerced to a string.

[123] + '' results in '123', and JSON.parse('123') results in 123.

[123, 4] + '' results in '123,4', and JSON.parse('123,4') results in a SyntaxError.

like image 108
junvar Avatar answered Feb 03 '26 16:02

junvar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!