gpt4 book ai didi

javascript - 无法访问 JSON 属性 - "Cannot read property of undefined"

转载 作者:行者123 更新时间:2023-11-30 11:38:26 25 4
gpt4 key购买 nike

我正在尝试使用维基百科 API 来检索文章标题和文章文本的片段。但是当我尝试访问这些属性时,出现错误“无法读取未定义的属性。”

这是我的 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);

任何有关如何访问属性“title”和“extract”的建议都将不胜感激。谢谢。

最佳答案

那是因为 pages 不是数组;它是一个对象,其中键是 id。所以你需要做:

console.log(response.query.pages[1122016].title);

这会起作用。例如,如果您想要“第一”页,那么

let pages = response.query.pages;
console.log(pages[Object.keys(pages)[0]].title);

请注意,我不确定 JS 对象中键的顺序是否有保证。

如果你想遍历页面,做

let pages = response.query.pages;
Object.keys(pages).forEach(id => {
let page = pages[id];
console.log(page.title, page.foo);
});

关于javascript - 无法访问 JSON 属性 - "Cannot read property of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43548569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com