使用带有vanilla JavaScript的嵌套在JSON对象中的已知名称访问属性的值

时间:2016-11-02 19:15:30

标签: javascript json

感谢您抽出宝贵时间阅读我的问题!我是JavaScript新手,无法找到以下问题的解决方案:

如何在名称动态更改的属性下访问嵌套在JSON对象中的属性的值?

JSON对象:

{
  "batchcomplete": "",
  "query": {
    "normalized": [
      {
        "from": "Theodore_Rubin",
        "to": "Theodore Rubin"
      }
    ],
    "pages": {
      "11820415": {
        "pageid": 11820415,
        "ns": 0,
        "title": "Theodore Rubin",
        "contentmodel": "wikitext",
        "pagelanguage": "en",
        "pagelanguagehtmlcode": "en",
        "pagelanguagedir": "ltr",
        "touched": "2016-02-12T17:34:52Z",
        "lastrevid": 138813300,
        "length": 34,
        "redirect": "",
        "new": "",
        "fullurl": "https://en.wikipedia.org/wiki/Theodore_Rubin",
        "editurl": "https://en.wikipedia.org/w/index.php?title=Theodore_Rubin&action=edit",
        "canonicalurl": "https://en.wikipedia.org/wiki/Theodore_Rubin"
      }
    }
  }
}

我正在尝试将属性fullurl的值分配给变量。我了解我可以使用括号和点表示法的组合来访问fullurl,例如query.pages["2123909"].fullurl。问题是属性名称["2123909"]随每个JSON请求而变化。

如何在不知道嵌套的属性名称的情况下访问fullurl属性的值?

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:3)

如果只有一个键,则可以获得data.query.pages var data = { "batchcomplete": "", "query": { "normalized": [ { "from": "Theodore_Rubin", "to": "Theodore Rubin" } ], "pages": { "11820415": { "pageid": 11820415, "ns": 0, "title": "Theodore Rubin", "contentmodel": "wikitext", "pagelanguage": "en", "pagelanguagehtmlcode": "en", "pagelanguagedir": "ltr", "touched": "2016-02-12T17:34:52Z", "lastrevid": 138813300, "length": 34, "redirect": "", "new": "", "fullurl": "https://en.wikipedia.org/wiki/Theodore_Rubin", "editurl": "https://en.wikipedia.org/w/index.php?title=Theodore_Rubin&action=edit", "canonicalurl": "https://en.wikipedia.org/wiki/Theodore_Rubin" } } } }; console.log(data.query.pages[Object.keys(data.query.pages)[0]].fullurl);的第一个元素。

pip install python_dateutil

答案 1 :(得分:0)

如果对象始终只有一个属性名称get the property name并通过括号表示法访问该属性:

var key = // see https://stackoverflow.com/q/6765864/218196
query.pages[key].fullurl

如果有多个属性,则迭代该对象,例如通过for...in。请参阅Access / process (nested) objects, arrays or JSON