user4509957
user4509957

Reputation: 69

parse json with jquery and display data in a html table

I need to parse the below json with jquery and display in a html table.
Display the values of key and count in a html table. The output should look like this.

{
    "key": "A",
    "count": 100
},
{
    "key": "AB",
    "count": 800
}

Any help is highly appreciated!

Upvotes: 1

Views: 543

Answers (1)

Jacques Marais
Jacques Marais

Reputation: 2756

Try the following:

var table = $("table");
var json = '{"took":32,"timed_out":false,"aggregations":{"2":{"doc_count_error_upper_bound":0,"sum_other_doc_count":447529,"buckets":[{"3":{"doc_count_error_upper_bound":2804,"sum_other_doc_count":152552,"buckets":[{"key":"d4","doc_count":6882},{"key":"r3","doc_count":6494}]},"rootkey":"AAA","doc_count":165928},{"3":{"doc_count_error_upper_bound":1574,"sum_other_doc_count":82914,"buckets":[{"key":"in","doc_count":4289},{"key":"d3","doc_count":3516}]},"rootkey":"BBB","doc_count":90719}]}}}';
json = $.parseJSON(json);
$.each(json.aggregations["2"].buckets, function(i, n){
    var rootkey = n.rootkey;
    n = n["3"];
    $.each(n.buckets, function(e, r){
        table.append("<tr><td>"+rootkey+"</td><td>"+r.key+"</td><td>"+r.doc_count+"</td></tr>");
    });
});

JSFiddle Here

Upvotes: 4

Related Questions