How to parse JSON string in Typescript

后端 未结 7 1500
[愿得一人]
[愿得一人] 2020-12-04 18:29

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

7条回答
  •  感动是毒
    2020-12-04 19:08

    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);
    

    (code in playground)

提交回复
热议问题