如何在json中获得正确的obj?

时间:2018-06-12 23:27:34

标签: jquery json

我有以下json:

{  
   "batchcomplete":"",
   "query":{  
      "pages":{  
         "53309836":{  
            "pageid":53309836,
            "ns":0,
            "title":"March 4 Trump",
            "contentmodel":"wikitext",
            "pagelanguage":"en",
            "pagelanguagehtmlcode":"en",
            "pagelanguagedir":"ltr",
            "touched":"2018-06-12T21:00:59Z",
            "lastrevid":828824621,
            "length":12173,
            "fullurl":"https://en.wikipedia.org/wiki/March_4_Trump",
            "editurl":"https://en.wikipedia.org/w/index.php?title=March_4_Trump&action=edit",
            "canonicalurl":"https://en.wikipedia.org/wiki/March_4_Trump"
         }
      }
   }
}

我通过跑步获得:

$.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=<?php echo $pageId; ?>&inprop=url&format=json&callback=?", {
  format: "json"
 }, function(data) {
  $.each(data.query, function(i) {
    console.log(JSON.stringify(data));
 });
});

我需要title

我尝试过:console.log(i.title);console.log(i.pages.title);

3 个答案:

答案 0 :(得分:1)

这会得到你的头衔。对象的$ .each函数返回键值对,以便您可以使用键获取或值。像这样。

$.each(data.query.pages, function(key, value) {
 console.log(data.query.pages[key].title)
// or
 console.log(value.title)
})

答案 1 :(得分:1)

  1. 使用data.query.pages然后使用标题索引获取值
    var data = {  
       "batchcomplete":"",
       "query":{  
          "pages":{  
             "53309836":{  
                "pageid":53309836,
                "ns":0,
                "title":"March 4 Trump",
                "contentmodel":"wikitext",
                "pagelanguage":"en",
                "pagelanguagehtmlcode":"en",
                "pagelanguagedir":"ltr",
                "touched":"2018-06-12T21:00:59Z",
                "lastrevid":828824621,
                "length":12173,
                "fullurl":"https://en.wikipedia.org/wiki/March_4_Trump",
                "editurl":"https://en.wikipedia.org/w/index.php?title=March_4_Trump&action=edit",
                "canonicalurl":"https://en.wikipedia.org/wiki/March_4_Trump"
             }
          }
       }
    }
    
      $.each(data.query.pages, function(index,value) {
        console.log(value.title);
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

您已经关闭了循环,但我会反序列化它,然后遍历所有页面以获得您想要的标题。

$.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=<?php echo $pageId; ?>&inprop=url&format=json&callback=?", {
format: "json"
}, function(data) {
    var d = JSON.stringify(data);
    $.each(d.query.pages, function() {
        console.log(this.title);
    });
});

或者,如果您知道自己要查找的具体页面,可以使用:

var d = JSON.stringify(data);
console.log(d.query.pages['53309836'].title);

希望有所帮助。