[英]Correct way to display formatted JSON data from rest api with React
[英]Unable to display varying json data recevied from api in react
我正在嘗試顯示從 api 收到的 json 數據。 但是 json 內部的數組長度和 json 數據的標簽是不固定的。 對於某些 json 響應,我沒有任何問題,但是當數組或標簽的長度發生更改時,我收到“未處理的拒絕(TypeError):無法讀取未定義的屬性“開始”(匿名函數)”我想要的是顯示整個數據並忽略數據為 null 的標簽。
{
"time": 3,
"annotations": [
{
"start": 4,
"end": 13,
"spot": "Mona Lisa",
"confidence": 0.8905,
"id": 70889,
"title": "Mona Lisa",
"uri": "http://en.wikipedia.org/wiki/Mona_Lisa",
"label": "Mona Lisa"
},
{
"start": 32,
"end": 44,
"spot": "oil painting",
"confidence": 0.8167,
"id": 22605,
"title": "Oil painting",
"uri": "http://en.wikipedia.org/wiki/Oil_painting",
"label": "Oil painting"
},
{
"start": 56,
"end": 64,
"spot": "Leonardo",
"confidence": 0.7723,
"id": 18079,
"title": "Leonardo da Vinci",
"uri": "http://en.wikipedia.org/wiki/Leonardo_da_Vinci",
"label": "Leonardo da Vinci"
},
{
"start": 83,
"end": 89,
"spot": "Louvre",
"confidence": 0.8942,
"id": 17546,
"title": "Louvre",
"uri": "http://en.wikipedia.org/wiki/Louvre",
"label": "Louvre"
},
{
"start": 93,
"end": 98,
"spot": "Paris",
"confidence": 0.7777,
"id": 22989,
"title": "Paris",
"uri": "http://en.wikipedia.org/wiki/Paris",
"label": "Paris"
}
],
"lang": "en",
"langConfidence": 1.0,
"timestamp": "2019-11-20T07:27:47.008"
}
QUERY 2:NASA成立於1958年。
Json 響應:
{
"time": 1,
"annotations": [
{
"start": 1,
"end": 5,
"spot": "NASA",
"confidence": 0.8143,
"id": 18426568,
"title": "NASA",
"uri": "http://en.wikipedia.org/wiki/NASA",
"label": "NASA"
}
],
"lang": "en",
"langConfidence": 0.5051,
"timestamp": "2019-11-20T07:29:02.227"
}
我現在在 for 循環中重復代碼 5 次,因為 json 范圍未知。 即 data3.map(y => y.annotations[1].start) data3.map(y => y.annotations[2].start)
以此類推,直到 4 點。
'''
const data1 = JSON.parse(res.data.jsondata);
const data2 = '[' + res.data.jsondata + ']';
const data3 = JSON.parse(data2);
console.log('loop log for faceId', data3)
let y = "";
for (let y of data3) {
const face = y.annotations
console.log('loop lenght', data3.map(y =>y.annotations.lenght))
this.setState({
lenght: data3.map(y => y.annotations.lenght),
Start: data3.map(y => y.annotations[0].start),
End: data3.map(y => y.annotations[0].end),
Spot: data3.map(y => y.annotations[0].spot),
Confidence: data3.map(y => y.annotations[0].confidence),
Id: data3.map(y => y.annotations[0].id),
Title: data3.map(y => y.annotations[0].title),
URL: data3.map(y => y.annotations[0].uri),
Label: data3.map(y => y.annotations[0].label),
)}
}
'''
無論您在哪里使用標簽示例,都必須進行未定義的檢查
const start = data.annotations ? data.annotations.start : "" ;
你必須做 null 檢查這些。 或者您也可以運行一個循環來檢查未定義和 null 檢查,然后忽略具有這些值的標簽。 這取決於您如何使用這些標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.