How to parse JSON in TypeScript

Introduction :

JSON or JavaScript Object Notation is an open standard file format used for transferring data. Parsing JSON data is really easy in Javascript or Typescript. Typescript doesn’t have any different methods for JSON parsing. We can use the same JSON.parse method used with JavaScript.

In this tutorial, I will show you how to use JSON.parse to parse JSON data in typescript with a couple of different examples.

Syntax :

The syntax of JSON.parse method is as below :

JSON.parse(text[, reviver])

It takes two parameters: the first parameter text is the JSON string. The second parameter is optional. It is a reviver function that can perform any operation on the JSON data before it returns it.

Simple example :

Let me show you one simple parsing example :

const data = `{
    "name" : "Alex",
    "age" : 20,
    "grade" : "A"
}`;

let json = JSON.parse(data);
console.log(json);
console.log(`Name: ${json.name}, Age: ${json.age}, Grade: ${json.grade}`);

Output :

{ name: 'Alex', age: 20, grade: 'A' }
Name: Alex, Age: 20, Grade: A

JSON.parse can parse any type of valid JSON data.

TypeScript json parse example

Exception :

If the JSON is not valid, it throws one SyntaxError exception. It doesn’t allow any single quote or trailing commas.

Parse nested JSON object :

Let’s try to parse one nested JSON object using JSON.parse :

const data = `{
    "name": "Alex",
    "age": 20,
    "grade": "A",
    "marks": [
        {"sub1" : 80},
        {"sub2" : 30}
    ]
}`;

let json = JSON.parse(data);
console.log(json);

console.log(`sub1: ${json.marks[0].sub1} sub2: ${json.marks[1].sub2}`);

Output :

{ name: 'Alex',  age: 20,  grade: 'A',  marks: [ { sub1: 80 }, { sub2: 30 } ] }
sub1: 80 sub2: 30

TypeScript nested json example

Using reviver :

Using the second parameter, reviver, we can modify the JSON object before the parse method returns it. We can also add one condition in the reviver to transform only specific values. The below example will multiply the value in the JSON object if it is a number :

const data = `{
    "one": 1,
    "two": 2,
    "three": "3",
    "four": 4,
    "others": [
        {
            "five": 5
        }
    ]
}`;

let json = JSON.parse(data, (k, v) => {
  if (typeof v === "number") {
    return v * 2;
  } else {
    return v;
  }
});
console.log(json);

Output :

{ one: 2, two: 4, three: '3', four: 8, others: [ { five: 10 } ] }

TypeScript json parse reviver example

You might also like: