How to parse JSON string in Typescript

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

    JSON.parse is available in TypeScript, so you can just use it :

    JSON.parse('{"name": "Bob", "error": false}') // Returns a value of type 'any'
    

    However, you will often want to parse a JSON object while making sure it matches a certain type, rather than dealing with a value of type any. In that case, you can define a function such as the following :

    function parse_json(
      json: string,
      type_definitions: { [Key in keyof TargetType]: (raw_value: any) => TargetType[Key] }
    ): TargetType {
      const raw = JSON.parse(json); 
      const result: any = {};
      for (const key in type_definitions) result[key] = type_definitions[key](raw[key]);
      return result;
    }
    

    This function takes a JSON string and an object containing individual functions that load each field of the object you are creating. You can use it like so:

    const value = parse_json(
      '{"name": "Bob", "error": false}',
      { name: String, error: Boolean, }
    );
    

提交回复
热议问题