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.

4
  • statements[1].predicate Commented Nov 15, 2013 at 12:32
  • I tried this one but it I did not see any outputs. Any idea, please? Commented Nov 15, 2013 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. Commented Nov 15, 2013 at 12:38
  • Have a look on this question: stackoverflow.com/questions/4992383/… Commented Nov 15, 2013 at 12:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.