How to parse JSON string in Typescript

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

    TS has a JavaScript runtime

    Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON, Object, and Math are also available in TS. Therefore we can just use the JSON.parse method to parse the JSON string.

    Example:

    const JSONStr = '{"name": "Bob", "error": false}'
    
    // The JSON object is part of the runtime
    const parsedObj = JSON.parse(JSONStr);
    
    console.log(parsedObj);
    // [LOG]: {
    //   "name": "Bob",
    //   "error": false
    // } 
    
    // The Object object is also part of the runtime so we can use it in TS
    const objKeys = Object.keys(parsedObj);
    
    console.log(objKeys);
    // [LOG]: ["name", "error"] 
    

    The only thing now is that parsedObj is type any which is generally a bad practice in TS. We can type the object if we are using type guards. Here is an example:

    const JSONStr = '{"name": "Bob", "error": false}'
    const parsedObj = JSON.parse(JSONStr);
    
    interface nameErr {
      name: string;
      error: boolean;
    }
    
    function isNameErr(arg: any): arg is nameErr {
      if (typeof arg.name === 'string' && typeof arg.error === 'boolean') {
        return true;
      } else {
        return false;
      }
    }
    
    if (isNameErr(parsedObj)) {
      // Within this if statement parsedObj is type nameErr;
      parsedObj
    }
    

提交回复
热议问题