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.
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
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 } ] }
You might also like:
- static in typescript with example
- Never type in typescript with example
- How to convert string to date in typescript
- Introduction to modules in typescript
- How to convert a string to an array of characters in TypeScript using split
- Typescript any explanation with example
- How to create a class in typescript with example
- How to convert any to string in typescript
- TypeScript string search method
- How to create an array of objects in TypeScript