我正在嘗試從我的 json(來自 http 請求)中創建一個物件,但它是一個純字串。
介面:
export interface CeleryTask {
uuid: string,
state: string,
received: string,
result: Chat,
}
export interface Chat {
id: number;
chatTitle: string;
chatId: string;
users: User[];
archived: boolean,
}
在我的服務中獲取請求:
loadAllSuccessTasksFromFlower(): Observable<CeleryTask[]> {
return this.http.get<CeleryTask[]>("http://localhost:5566/api/tasks?state=SUCCESS")
.pipe(map(response => Object.entries(response)
.map(entry => ({
uuid: entry[0],
state: entry[1].state,
received: entry[1].received,
result: entry[1].result
}))))
}
HTTP 回應:
{
"67fe1783-4451-4fa5-838e-b78279fd5c07":{
"uuid":"67fe1783-4451-4fa5-838e-b78279fd5c07",
"name":"upload.tasks.importWorkTask",
"state":"SUCCESS",
"received":1668285215.4455156,
"sent":null,
"started":1668285219.4739492,
"rejected":null,
"succeeded":1668285419.1474545,
"failed":null,
"retried":null,
"revoked":null,
"args":"('C:\\Users\\xx\\AppData\\Local\\Temp\\xxx', 'xx.pdf')",
"kwargs":"{}",
"eta":null,
"expires":null,
"retries":0,
"result":"{'id': 9, 'chatTitle': 'My Chat'}",
"exception":null,
"timestamp":1668285419.1474545,
"runtime":199.67199999999866,
"traceback":null,
"exchange":null,
"routing_key":null,
"clock":599,
"client":null,
"root":"67fe1783-4451-4fa5-838e-b78279fd5c07",
"root_id":"67fe1783-4451-4fa5-838e-b78279fd5c07",
"parent":null,
"parent_id":null,
"children":[
],
"worker":"celery@xxx"
}
當我 console.log 結果:
{
"uuid": "67fe1783-4451-4fa5-838e-b78279fd5c07",
"state": "SUCCESS",
"received": 1668285215.4455156,
"result": "{'id': 9, 'chatTitle': 'My Chat'}"
}
id & chatTitle 不是聊天物件,它是一個純字串。所以無法訪問object.result.chatTitle
知道如何解決這個問題嗎?
uj5u.com熱心網友回復:
從接收到的字串中獲取物件的一種方法是
result: JSON.parse(entry[1].result);
構建一個型別保護讓 typescript 明白你真的有一個 Chat 物件
function isChat(o: any): o is Chat {
// check whatever is necessary to be a Chat object
return "id" in o && "chatTitle" in o
}
像這樣使用 typeguard
const parsed = JSON.parse(jsonString);
if (isChat(parsed)) {
// do something with now correctly typed object
} else {
// error handling; invalid JSON format
}
有關更多資訊,請參閱https://stackoverflow.com/a/62438143/7869582
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532562.html
