我正在嘗試使用維基百科API檢索文章標題和文章的文本片段。但是當我嘗試訪問這些屬性時,出現錯誤「無法讀取未定義的屬性」。JSON屬性無法訪問 - 「無法讀取未定義的屬性」
這裏是我的JSON響應:
{
"batchcomplete": "",
"continue": {
"gsroffset": 10,
"continue": "gsroffset||"
},
"query": {
"pages": {
"13834": {
"pageid": 13834,
"ns": 0,
"title": "\"Hello, World!\" program",
"index": 6,
"extract": "<p>A <b>\"Hello, World!\" program</b> is a computer program that outputs or displays \"Hello, World!\" to a user. Being a very simple program in most programming languages, it is often used to illustrate the</p>..."
},
"6710844": {
"pageid": 6710844,
"ns": 0,
"title": "Hello",
"index": 1,
"extract": "<p><i><b>Hello</b></i> is a salutation or greeting in the English language. It is first attested in writing from 1826.</p>..."
},
"1122016": {
"pageid": 1122016,
"ns": 0,
"title": "Hello! (magazine)",
"index": 7,
"extract": "<p><i><b>Hello</b></i> (stylised as <i><b>HELLO!</b></i>) is a weekly magazine specialising in celebrity news and human-interest stories, published in the United Kingdom since 1988. It is the United Kingdom</p>..."
}
}
}
}
我曾嘗試寫代碼的幾個不同的方式。例如,這個工作(登錄控制檯頁面爲對象):
console.log(response.query.pages);
但是,這將返回我上面寫的錯誤(「無法讀取的未定義的屬性」):
console.log(response.query.pages[0].title);
任何將不勝感激如何訪問屬性「標題」和「提取」的建議。謝謝。
爲了讓他們的數組:'Object.keys(頁).MAP(ID =>頁[ID])' –
*「。注意,我相信如果JS對象中的鍵的順序是有保證的。「*不與'Object.keys'或'for-in',不。它使用'Object.getOwnPropertyNames'。 (在這種情況下,使用'Object.getOwnPropertyNames',它將按照數字順序升序,因爲這些鍵適合數組索引的定義[是的,即使它不是數組]。) –
@RickHitchcock:不用這些鍵,它們符合「數組索引」的定義。歷史上,實施過程與其他過程不同。 –