我正在尝试使用Wikipedia 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”的任何建议将不胜感激。感谢。
答案 0 :(得分:4)
那是因为页面不是数组;它是键是id的对象。所以你需要这样做:
console.log(response.query.pages[1122016].title);
这会奏效。如果你想要&#34;首先&#34;例如,页面,然后
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);
});
答案 1 :(得分:0)
您好伙伴,
如果您正在使用React之类的框架或使用开发服务器(例如,使用npm start
或其他类似工具)的其他框架来签出此线程,则开发服务器可能尝试执行console.log(response.foo.bar)
之前之类的操作时会崩溃,它会在重新加载数据时刷新。
具体来说,我的开发服务器崩溃并显示Cannot read property 'bar' of undefined
类型的消息,我当时想,“到底发生了什么!!”。解决方案:将婴儿放在try / catch块中:
try {
console.log(rate['bar'].rate)
} catch (error) {
console.log(error)
}
为什么?如果您的应用具有默认状态(例如,甚至是一个空数组),那么它会在从远程源接收到数据之前尝试console.log
响应,它将成功记录您的空状态,但是如果您尝试在console.log
或其他任何地方引用您希望从远程源接收到的对象部分,开发服务器将尝试在初始加载和崩溃时引用不存在的对象,然后才有机会当它实际上是通过API或其他任何方式从远程源接收到时引用它。
希望这对某人有帮助!
答案 2 :(得分:-1)
我不确定您使用哪种语言来解析JSON(看起来像是来自console.log的Javascript?)但问题是query.pages是字典,而不是数组,所以它不能通过索引进行迭代,只能通过密钥进行迭代。
所以你想要(伪代码):
for (key in response.query.keys)
{
console.log(response.query[key].title);
}