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.
1. JSON.parse example
function parseArray(json: string): string[] {
const array: string[] = JSON.parse(json);
if (array instanceof Array) {
return array;
}
throw new Error('Incorrect type!');
}
// Example:
const json: string = '[1, 2, 3]';
const array: string[] = parseArray(json);
console.log(array); // [1,2,3]
console.log(array[0]); // 1
console.log(array[1]); // 2
console.log(array[2]); // 3
Output:
[ 1, 2, 3 ]
1
2
3