Why does JSON.parse work on 1 element arrays?

Viewed 111

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?

2 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.

It attempts to treat the array as a string.

console.log([123].toString()); // Valid JSON
console.log([123, 456].toString()); // Not valid JSON
console.log(['string'].toString()); // Not valid JSON

Related