How to parse JSON string in Typescript

后端 未结 7 1461
[愿得一人]
[愿得一人] 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:25

    You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:

    import { Field } from "sparkson";
    class Response {
       constructor(
          @Field("name") public name: string,
          @Field("error") public error: boolean
       ) {}
    }
    

    The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.

    0 讨论(0)
提交回复
热议问题