jquery datatables嵌套值json

时间:2016-05-31 20:23:22

标签: jquery json datatables

我想从以下json生成一个包含姓名,职位,电话和电子邮件的数据表。但我现在不知道如何访问名称和嵌套值。无法更改json。

JSON:

palette

结果:

{
  "key1" : "somevalue",
  "key2" : "somevalue2",
  "contacts" : {
    "John Doe" : {
      "position" : "CEO",
      "phone" : "1234-5678-0",
      "email" : "john@company.com"
    },
    "Elvis Presley" : {
      "position" : "Singer",
      "phone" : "0234-5678-0",
      "email" : "elvis@heaven.com"
    },
    "Albert Einstein" : {
      "position" : "Thinker",
      "phone" : "0000-8888-0",
      "email" : "albert@universe.gov"
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用ajax.dataSrc选项操作数据。

例如:

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;
       }
    }
});

请参阅this jsFiddle以获取代码和演示。

答案 1 :(得分:0)

如果你有名为data的变量,那么你可以访问data.contacts,然后从那里你可以这样做:

<div id="content">
   lots of random stuff<br />
   lots of random stuff<br />
   lots of random stuff<br />
</div>
<footer id="foot"><p></p></footer>

答案 2 :(得分:0)

示例: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" : "john@company.com"
    },
    "Elvis Presley" : {
      "position" : "Singer",
      "phone" : "0234-5678-0",
      "email" : "elvis@heaven.com"
    },
    "Albert Einstein" : {
      "position" : "Thinker",
      "phone" : "0000-8888-0",
      "email" : "albert@universe.gov"
    }
}};
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);