Is there a way to parse strings as JSON in TypeScript?
For example in JavaScript, we can use JSON.parse()
. Is there a similar function in TypeScript?
I have a JSON object string as follows:
JavaScript
x
2
1
{"name": "Bob", "error": false}
2
Advertisement
Answer
TypeScript is (a superset of) JavaScript, so you just use JSON.parse
as you would in JavaScript:
JavaScript
1
2
1
let obj = JSON.parse(jsonString);
2
Only that in TypeScript you can also have a type for the resulting object:
JavaScript
1
9
1
interface MyObj {
2
myString: string;
3
myNumber: number;
4
}
5
6
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
7
console.log(obj.myString);
8
console.log(obj.myNumber);
9