簡體   English   中英

如何將 JSON object 反序列化為接口 TypeScript

[英]How to deserialize JSON object into an interface TypeScript

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

我不確定是什么原因造成的。 接口 model 匹配 JSON 結構。

看起來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 的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM