How to Parse Json String in Typescript
Is There a Way to Parse Strings as Json in Typescript. Example: in Js, We Can Use Json. Parse(). Is There a Similar Function in Typescript? I Have a Json...
Is there a way to parse strings as JSON in Typescript.
Example: In JS, we can use JSON.parse(). Is there a similar function in Typescript?
I have a JSON object string as follows:
{"name": "Bob", "error": false}
10 Answers
Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to 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);
Type-safe JSON.parse
You can continue to use JSON.parse, as TypeScript is a superset of JavaScript:
This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written.
There is a problem left: JSON.parse returns any, which undermines type safety (don't use any).
Here are three solutions for stronger types, ordered by ascending complexity:
Must Read
1. User-defined type guards
// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }
// Validate this value with a custom type guard (extend to your needs)
function isMyType(o: any): o is MyType {
return "name" in o && "description" in o
}
const json = '{ "name": "Foo", "description": "Bar" }';
const parsed = JSON.parse(json);
if (isMyType(parsed)) {
// do something with now correctly typed object
parsed.description
} else {
// error handling; invalid JSON format
}
isMyType is called a type guard. Its advantage is, that you get a fully typed object inside truthy if branch.