EN
JavaScript - convert json text to array variable
3 points
In this article, we would like to show you how to convert a JSON text to an array variable in JavaScript.
xxxxxxxxxx
1
function parseArray(json) {
2
var array = JSON.parse(json);
3
4
if(array instanceof Array) {
5
return array;
6
}
7
8
throw new Error('Incorrect type!');
9
}
10
11
// Example:
12
13
var json = '[1, 2, 3]';
14
var array = parseArray(json);
15
16
console.log(array); // 1,2,3
17
18
console.log(array[0]); // 1
19
console.log(array[1]); // 2
20
console.log(array[2]); // 3
Output:
xxxxxxxxxx
1
1,2,3
2
3
1
4
2
5
3