简体   繁体   English

如何使用jQuery循环遍历JSON文件

[英]How to loop through JSON file using jQuery

I am trying loop through the following JSON file below: 我正在尝试循环通过以下JSON文件:

 {
     "statements": [{
         "subject": "A"
     }, {
         "predicate": "B"
     }, {
         "object": "C"
     }, {
         "subject": "D"
     }, {
         "predicate": "E"
     }, {
         "object": "F"
     }]
 }

As you can see, there are two subjects, two predicates and two objects. 如您所见,有两个主题,两个谓词和两个对象。 I would like to get, for instance, the value "predicate":"E" . 例如,我想获得值"predicate":"E" How can I do this using jQuery or D3 Javascript library. 我怎么能使用jQuery或D3 Javascript库来做到这一点。 My code below retrieves the first subject "subject":"A" . 我的下面的代码检索第一个主题"subject":"A"

$.each(data.statements[0], function(i, v){
console.log(v.uriString);
});

or in D3 (I do not know how to do this in D3): 或者在D3中(我不知道如何在D3中执行此操作):

d3.json("folder/sample.json", function(error, graph) 
{  // Code is here for getting data from JSON file }

Could anyone please help me loop through the JSON file above and retrieve some particular data either with jQuery or D3 Javascript. 任何人都可以帮我循环上面的JSON文件,并使用jQuery或D3 Javascript检索一些特定的数据。 Thank you for your help in advance. 提前谢谢你的帮助。

The reason why your code returns the first item is beacuse you selected it with data.statments[0] and afterwards loop over that one item. 您的代码返回第一个项目的原因是您没有使用data.statments[0]选择它,然后循环遍历该项目。

With jQuery you can use the grep-method like this: 使用jQuery,你可以像这样使用grep-method:

var arrayWithItem = jQuery.grep(data.statements, function( obj ) {
  return obj.predicate == "E";
});

You can read more about the grep-method here 您可以在此处阅读有关grep-method的更多信息

With D3js I'm not sure, I guess you have to loop through it with an if-statement. 使用D3js我不确定,我猜你必须用if语句循环它。

Try this: 尝试这个:

$(data.statements).each(function (i) {
    var d = data.statements[i];
    $.each(d, function (k, v) { //get key and value of object
        $("body").append("<p>"+k + ":" + v+"</p>");
    });
})

Fiddle here. 在这里小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM