我正在尝试使用维基百科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:不用这些键,它们符合“数组索引”的定义。历史上,实施过程与其他过程不同。 –