Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through JSON file using jQuery

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.

like image 437
user2864315 Avatar asked Mar 27 '26 16:03

user2864315


1 Answers

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.

like image 52
codingrose Avatar answered Mar 30 '26 05:03

codingrose