0

I have this json data that I'm trying to put into an html table:

{
"users":{
  "key":[
     "3128",
     "3108"
  ],
  "name":[
     "jason",
     "fred"
  ]
 }
}

I wanted to make both key and name to separate columns in the table. I'm using this jquery code. Its placing the data properly in the in each column, however its duplicating the data. I'm guessing its because I'm looping through multiple times.

var url = "http://localhost/test.php";
$.getJSON(url,function(data){
 var table = '<table><thead><tr><th>Key</th><th>Name</th></tr></thead><tbody>';
    $.each(data, function(i, param) {
            $.each(param['key'], function(l, k) {
            $.each(param['name'], function(l, p) {
                    table +="<tr><td>" + k + "</td>"+"<td>" + p  + "</td></tr>";
                                                });
                                          });
                                     });
     table += '</tbody></table>';
   $("#jsondata").html( table );
});

How do I stop duplicating the data in the columns I'm creating?

Help is greatly appreciated!

1 Answer 1

1

I would do it like this (inside the closure of the getJSON function):

var table = '<table><thead><tr><th>Key</th><th>Name</th></tr></thead><tbody>';
var users = data.users;
$.each(data.users.key, function(i, key) {
    table +="<tr><td>" + key + "</td>"+"<td>" + data.users.name[i]  + "</td></tr>";
});
table += '</tbody></table>';

Here the code in jsFiddle: http://jsfiddle.net/QchnP/

A note: In the line $.each(data, function(i, param) { you will iterate over each property of the JSON dictionary, which is not necessary (if you only have an interest in the users value).

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

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.