I don't understand why JSON.parse('[123]')
returns an integer 123
? Shouldn't it return an array [123]
?
Here is the fiddle.
How can I get an array of a single integer after JSON.parse()
?
I don't understand why JSON.parse('[123]')
returns an integer 123
? Shouldn't it return an array [123]
?
Here is the fiddle.
How can I get an array of a single integer after JSON.parse()
?
-
6
Array.isArray(JSON.parse('[123]')) === true
. – beatgammit Commented Jul 19, 2013 at 5:54 -
>> JSON.parse('[123]') // [123]
- what r u talkin bout ? and it is ==123 and not ===123. js just tries to extract numbers – Royi Namir Commented Jul 19, 2013 at 6:15
2 Answers
Reset to default 10It is an array, only when it is printed, the brackets are not printed.
Take a look at this one with two items: http://jsfiddle/2z355/4/
It prints as 123,456
, also without brackets.
el.innerHTML = JSON.parse('[123]'); // The one item: 123
el.innerHTML = JSON.parse('[123]')[0]; // First item of array: 123
el.innerHTML = JSON.parse('[123,456]') // Both values: 123,456;
el.innerHTML = JSON.parse('[123,456]')[0] // First item: 123;
And also
el.innerHTML = typeof JSON.parse('123'); // number
el.innerHTML = typeof JSON.parse('[123]'); // object *)
I'd have expected 'array' there, but it turns out to be an object. Maybe I've been PHPing too much lately. Nevertheless, it's not a number. :) Fortunately the next line will work (thanks to icktoofay).
el.innerHTML = JSON.parse('[123]') instanceof Array; // true
It is an array of a single integer; it's just that a quirk of JavaScript makes the string representation of an array be the string representations of the elements joined by mas, without the [
and ]
.
You know it's an array because
result instanceof Array
JSON.stringify(result) === '[123]'