. Advertisement .
..3..
. Advertisement .
..4..
There are various ways to parse a JSON string in TypeScript, but the most common way is to use the JSON.parse() function used in JavaScript, as TypeScript is a superset of JavaScript.
How to parse a JSON string in TypeScript
Solution 1: Using JSON.parse()
The data that we receive from a web server is always a string. Parsing with JSON.parse() will simply turn all of the data into an object.
Since TypeScript is a superset of JavaScript (you can basically use any JavaScript code in TypeScript), we can use the JSON.parse() just the same as we would in JavaScript.
The syntax of JSON.parse():
JSON.parse(text, reviver)
Parameter:
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.
Example 1:
const jsonString = '{ "brand": "Tutopal", "year": 2022 }';
interface Car {
brand: string ;
year: number;
}
//Parse
let obj: Car = JSON.parse(jsonString);
//print out
console.log(obj.brand);
console.log(obj.year);
Output:
"Tutopal"
2022
Example 2:
//our object
type Fruit = {
name: string ;
amount: number;
}
//Parse
let obj: Fruit = JSON.parse('{ "name": "Apple", "amount": 5 }');
//print out
console.log(obj.name);
console.log(obj.amount);
Output:
"Apple"
5
The parsed JSON string is loaded into a TypeScript class object. And we can access the properties of a class object in the same way that we can access the elements of a JSON object.
As you can see, the two examples above explicitly type the object. If you do not do that, it gets assigned a type of any (which is BAD).
const jsonString = '{ "brand": "Tutopal", "year": 2022 }';
//Parse
let obj = JSON.parse(jsonString);
//print out
console.log(obj.brand);
console.log(obj.year);
Solution 2: With type assertion
You can always use a type assertion to set the type of a parsed value.
const obj = JSON.parse(jsonString) as Car;
Example:
const jsonString = '{ "brand": "Tutopal", "year": 2022 }';
interface Car {
brand: "Tutopal" ;
year: 2022;
}
const obj = JSON.parse(jsonString) as Car; //type assertion
console.log(obj.brand);
console.log(obj.year);
Solution 3: Type Guard
You can always have a property as optional if you are not sure that it will exist on the object, or use a union type if the property has different types, but try to be as strict at your type definition as possible.
For example, when you have a union ‘number | null’, you can not apply methods that only use on type ‘number’.
You can fix it by doing the following:
const jsonString = '{ "brand": "Tutopal", "year": 2022 }';
type Car = {
brand: string ;
year: number | null; //Union Type
}
const obj: Car = JSON.parse(jsonString);
if (typeof obj.year === ‘number’) {
// at this moment, obj.year is a number
console.log(obj.year.toFixed(1);
}
Output:
2022.0
As we have narrowed the union, ‘obj.year’ is a number inside the if statement and can be applied to methods that only use on type ‘number’.
Summary
The tutorial has shown how to parse a JSON string in TypeScript, using different methods that we would apply in JavaScript. Please make sure to clearly type your result, or it might get a type of any, which is not ideal.
Read more
Leave a comment