Reputation: 700
I want to generate a datatable with name, position, phone and email from the following json. But I don't now how to access the name and the nested value. Changing the json is not possible.
JSON:
{
"key1" : "somevalue",
"key2" : "somevalue2",
"contacts" : {
"John Doe" : {
"position" : "CEO",
"phone" : "1234-5678-0",
"email" : "[email protected]"
},
"Elvis Presley" : {
"position" : "Singer",
"phone" : "0234-5678-0",
"email" : "[email protected]"
},
"Albert Einstein" : {
"position" : "Thinker",
"phone" : "0000-8888-0",
"email" : "[email protected]"
}
}
RESULT:
+-----------------+----------+-------------+---------------------+
| NAME | POSITION | PHONE | EMAIL |
+-----------------+----------+-------------+---------------------+
| John Doe | CEO | 1234-5678-0 | [email protected] |
+-----------------+----------+-------------+---------------------+
| Elvis Presley | Singer | 0234-5678-0 | [email protected] |
+-----------------+----------+-------------+---------------------+
| Albert Einstein | Thinker | 0000-8888-0 | [email protected] |
+-----------------+----------+-------------+---------------------+
Upvotes: 2
Views: 436
Reputation: 58880
You can manipulate the data using ajax.dataSrc
option.
For example:
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/4nnmy',
dataSrc: function(json){
var data = [];
for(var contact_name in json.contacts){
var contact = json.contacts[contact_name];
data.push([
contact_name,
contact['position'],
contact['phone'],
contact['email']
]);
}
return data;
}
}
});
See this jsFiddle for code and demonstration.
Upvotes: 2
Reputation: 3634
Example : https://jsfiddle.net/9aLvd3uw/204/
Html :
<table>
<thead>
<tr>
<th>NAME</th>
<th>POSITION</th>
<th>PHONE</th>
<th>EMAIL</th>
</tr>
</thead>
<tbody id="myTbody">
</tbody>
</table>
js :
var data = {
"key1" : "somevalue",
"key2" : "somevalue2",
"contacts" : {
"John Doe" : {
"position" : "CEO",
"phone" : "1234-5678-0",
"email" : "[email protected]"
},
"Elvis Presley" : {
"position" : "Singer",
"phone" : "0234-5678-0",
"email" : "[email protected]"
},
"Albert Einstein" : {
"position" : "Thinker",
"phone" : "0000-8888-0",
"email" : "[email protected]"
}
}};
var contacts = data.contacts;
var string = '';
for (name in contacts){
string += '<tr><td>' +name + '</td><td>' + contacts[name].position + '</td><td>' + contacts[name].phone + '</td><td>' + contacts[name].email + '</td></tr>' ;
}
$("#myTbody").html(string);
Upvotes: 0
Reputation: 304
If you have the variable named data, then you can access data.contacts, and from there you can do this:
for(var contact in data.contacts) {
if(data.contacts.hasOwnProperty(contact)) {
// Do whatever with data.contacts[contact].position
// Do whatever with data.contacts[contact].phone
// Do whatever with data.contacts[contact].email
}
}
Upvotes: 0