EN
TypeScript - convert json text to array variable
0 points
In TypeScript, it is possible to convert JSON text to array variable in the following way.
xxxxxxxxxx
1
function parseArray(json: string): string[] {
2
const array: string[] = 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
const json: string = '[1, 2, 3]';
14
const array: string[] = 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
1
3
2
4
3