snippetjavascriptCritical
How to parse JSON string in Typescript
Viewed 0 times
typescripthowparsestringjson
Problem
Is there a way to parse strings as JSON in TypeScript?
For example in JavaScript, we can use
I have a JSON object string as follows:
For example in JavaScript, we can use
JSON.parse(). Is there a similar function in TypeScript?I have a JSON object string as follows:
{"name": "Bob", "error": false}
Solution
TypeScript is (a superset of) JavaScript, so you just use
Only that in TypeScript you can also have a type for the resulting object:
(code in playground)
JSON.parse as you would in JavaScript:let obj = JSON.parse(jsonString);Only that in TypeScript you can also have a type for the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);(code in playground)
Code Snippets
let obj = JSON.parse(jsonString);interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);Context
Stack Overflow Q#38688822, score: 395
Revisions (0)
No revisions yet.