【问题标题】:How to deserialize JSON object into an interface TypeScript如何将 JSON 对象反序列化为接口 TypeScript
【发布时间】:2020-12-03 23:25:26
【问题描述】:
const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=330746772378877954');
const json = await response.json(); 
const user: User = JSON.parse(json);
interface User {
    id: string;
    username: string;
    avatar: string;
}

在最后一行JSON.parse(json),我收到一条错误消息:

Unhandled Rejection (SyntaxError): Unexpected token o in JSON at position 1

我不确定是什么原因造成的。接口模型匹配 JSON 结构。

【问题讨论】:

  • 已经解析过了。这就是.json() 所做的。
  • 您看到的错误是因为您正在尝试解析已解析的 json 字符串。因此,当您运行JSON.parse(object) 时,它必须尝试弄清楚要做什么,因此它将变成JSON.parse('[object Object]') 的对象串起来

标签: javascript json typescript fetch


【解决方案1】:

看起来JSON.parse(json) 是不必要的。我所要做的就是

const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=330746772378877954');
const user: User = await response.json(); 

感谢@Taplar 的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多