Languages
[Edit]
EN

TypeScript - convert json text to array variable

0 points
Created by:
Richard-Bevan
413

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

Alternative titles

  1. TypeScript - how to convert json text to array variable?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join