3

I am trying loop through the following JSON file below:

 {
     "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". How can I do this using jQuery or D3 Javascript library. My code below retrieves the first subject "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.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. Thank you for your help in advance.

Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
Mod
  • 5,091
  • 7
  • 28
  • 47
  • `statements[1].predicate` – adeneo Nov 15 '13 at 12:32
  • I tried this one but it I did not see any outputs. Any idea, please? – Mod Nov 15 '13 at 12:36
  • `statements[1].predicate` would only work if he already knows the index of the item he needs. This will return the predicate value of the second object in the statements array. Also he asked for the one with predicate "E", so that would mean he has to use: `statements[4].predicate`. – Leon Hooijer Nov 15 '13 at 12:38
  • Have a look on this question: http://stackoverflow.com/questions/4992383/use-jquerys-find-on-json-object – Joche Nov 15 '13 at 12:39

2 Answers2

1

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.

With jQuery you can use the grep-method like this:

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

You can read more about the grep-method here

With D3js I'm not sure, I guess you have to loop through it with an if-statement.

Leon Hooijer
  • 584
  • 3
  • 16
1

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.

codingrose
  • 15,563
  • 11
  • 39
  • 58