JSON 属性无法访问 - “无法读取未定义的属性”

Sco*_*ott 2 javascript json

我正在尝试使用 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>..."
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了几种不同的编写代码的方法。例如,这有效(将页面记录为控制台中的对象):

console.log(response.query.pages);
Run Code Online (Sandbox Code Playgroud)

但这会返回我上面写的错误(“无法读取未定义的属性”):

console.log(response.query.pages[0].title);
Run Code Online (Sandbox Code Playgroud)

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

Lua*_*ico 6

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

console.log(response.query.pages[1122016].title);
Run Code Online (Sandbox Code Playgroud)

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

let pages = response.query.pages;
console.log(pages[Object.keys(pages)[0]].title);
Run Code Online (Sandbox Code Playgroud)

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

如果要遍历页面,请执行

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