How To Parse A JSON String In TypeScript

How to parse a JSON string in TypeScript

In this tutorial, we will show you how to parse a JSON string in TypeScript. There are various ways to do it, but the most common one is using the JSON.parse() method.

Parse a JSON string in TypeScript 

Method 1: Using JSON.parse() 

All the data that we receive from the web server are strings. And since then, if we try to access it poverty like this: 

Example 1: 

const jsonString = '{ "name": "LearnShareIt.com", "year": 2022 }';

console.log(jsonString.name);
console.log(jsonString.year);

Output: 

undefined
undefined

To deal with that, JavaScript has supported us with the JSON.parse() method to turn strings into objects.  

As TypeScript is a superset of JavaScript (the code you write in JavaScript will be basically runnable in TypeScript), we can use the JSON.parse() just the same as we would in JavaScript.

Syntax:

JSON.parse(text, reviver)

Parameters:

  • text: the string to parse
  • reviver (optional): a function that modifies the result before returning. 

Return value: Object, Array, string, number, boolean, or null value based on the given JSON text.

Let’s apply that to fix example 1: 

const jsonString = '{ "name": "LearnShareIt.com", "year": 2022 }';
const result = JSON.parse(jsonString);

console.log(result.name);
console.log(result.year);

Output:

LearnShareIt.com
2022

The JSON string is now work as an object, and we can access its properties just like a normal JSON object. Example 2:

type person = {
  name: string ;  
  age: number;
  job: string;
  phone: string;
  address: string;

};

var myString = '{ "name": "Tom", "age": 25, "job": "teacher", "phone": "0123456789", "address": "123xyz" }';
let obj: person = JSON.parse(myString);

console.log(obj);
console.log(obj.name);
console.log(obj.age);

Output:

{
  name: 'Tom',
  age: 25,
  job: 'teacher',
  phone: '0123456789',
  address: '123xyz'
}
Tom
25

Method 2: With type assertion

In our two examples above, we explicitly type our object so that the object will not get the type any. Besides that, you can also always use a type assertion to set the type of a parsed value.

const obj = JSON.parse(myString) as person;

Completed code for example 2: 

type person = {
  name: string ;  
  age: number;
  job: string;
  phone: string;
  address: string;
};

var myString = '{ "name": "Tom", "age": 25, "job": "teacher", "phone": "0123456789", "address": "123xyz" }';
let obj = JSON.parse(myString) as person ;

console.log(obj);

Output:

{
  name: 'Tom',
  age: 25,
  job: 'teacher',
  phone: '0123456789',
  address: '123xyz'
}

Summary

This tutorial has guided you step by step on how to parse a JSON string in TypeScript. The idea is to use the built-in method JSON.parse() and type our object so that it will not get the type of ‘any’.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *