Convertir les données json en table html [fermé]


112

Existe-t-il une bibliothèque jQuery ou javascript qui génère une table dynamique à partir de données json? Je ne veux pas définir les colonnes, la bibliothèque doit lire les clés dans le hachage json et générer des colonnes.

Bien sûr, je peux moi-même parcourir les données json et générer la table html. Je veux juste savoir s'il existe une telle bibliothèque que je peux simplement réutiliser.


Je pense que trirand.com/blog est ce que vous recherchez. Il prend JSON et le convertit en une grille.
— Gokul NK

1
Eh bien, merci pour les réponses. Mais pour suffire à mes besoins, j'en ai écrit un pour moi-même. jsfiddle.net/manishmmulani/7MRx6
— Manish Mulani

2
Vous pouvez également utiliser ce projet simple sur Github: Json-To-HTML-Table
— Afshin Mehrabani

Plus facilement en 2020, il suffit d'utiliser github.com/arters/Convert-json-data-to-a-html-template
— kkasp

Réponses:


136

Merci à tous pour vos réponses. J'en ai écrit un moi-même. Veuillez noter que cela utilise jQuery.

Extrait de code:

var myList = [
  { "name": "abc", "age": 50 },
  { "age": "25", "hobby": "swimming" },
  { "name": "xyz", "hobby": "programming" }
];

// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(myList, selector);

  for (var i = 0; i < myList.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = myList[i][columns[colIndex]];
      if (cellValue == null) cellValue = "";
      row$.append($('<td/>').html(cellValue));
    }
    $(selector).append(row$);
  }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records.
function addAllColumnHeaders(myList, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < myList.length; i++) {
    var rowHash = myList[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);

  return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body onLoad="buildHtmlTable('#excelDataTable')">
  <table id="excelDataTable" border="1">
  </table>
</body>


Salut @ Manish-mulani cela n'a pas fonctionné pour moi, pourriez-vous vérifier à nouveau
— Nish

1
@Nish Avez-vous vérifié jsfiddle.net/manishmmulani/7MRx6
— Manish Mulani

1
Bonjour, j'ai essayé d'obtenir les données à partir d'une URL, mais cela ne semble pas fonctionner

3
Salut. Celui-ci fonctionne pour moi. Cependant j'ai une question. Pourquoi n'y a-t-il pas d'ouverture tret de tdbalises? Merci.
— Cyval

function addAllColumnHeaders(myList)- est faux. devrait être function addAllColumnHeaders(myList,selector). BTW cela fonctionne parfaitement !!
— Shirker

61

J'ai réécrit votre code en vanilla-js, en utilisant des méthodes DOM pour empêcher l'injection html.

Démo

var _table_ = document.createElement('table'),
  _tr_ = document.createElement('tr'),
  _th_ = document.createElement('th'),
  _td_ = document.createElement('td');

// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(arr) {
  var table = _table_.cloneNode(false),
    columns = addAllColumnHeaders(arr, table);
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {
    var tr = _tr_.cloneNode(false);
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {
      var td = _td_.cloneNode(false);
      cellValue = arr[i][columns[j]];
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
      tr.appendChild(td);
    }
    table.appendChild(tr);
  }
  return table;
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(arr, table) {
  var columnSet = [],
    tr = _tr_.cloneNode(false);
  for (var i = 0, l = arr.length; i < l; i++) {
    for (var key in arr[i]) {
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
        columnSet.push(key);
        var th = _th_.cloneNode(false);
        th.appendChild(document.createTextNode(key));
        tr.appendChild(th);
      }
    }
  }
  table.appendChild(tr);
  return columnSet;
}

document.body.appendChild(buildHtmlTable([{
    "name": "abc",
    "age": 50
  },
  {
    "age": "25",
    "hobby": "swimming"
  },
  {
    "name": "xyz",
    "hobby": "programming"
  }
]));


1
Est-il possible de faire fonctionner cela avec un objet json imbriqué?
— Janac Meena

@JanacMeena Je pense que vous auriez besoin de tables à n dimensions pour cela.
— Oriol

C'est vrai. Tableaux dans les tableaux. De plus, j'ai découvert des treemaps zoomables qui permettent d'imbriquer json
— Janac Meena

Cette même fonction mais en retournant un tableau pivotant, serait magnifique
— ndelucca

1
@Shai utilise JSON.parse (yourVariable) et l'envoie à buldHTMLTable
— xSx

13

Vous pouvez utiliser un simple plugin jQuery jPut

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"email1@domain.com"},{"name": "name2","link":"email2@domain.com"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

13

Consultez le plugin JSON2HTML http://json2html.com/ pour jQuery. Il vous permet de spécifier une transformation qui convertirait votre objet JSON en modèle HTML. Utilisez builder sur http://json2html.com/ pour obtenir l'objet de transformation json pour tout modèle html souhaité. Dans votre cas, ce serait une table avec une ligne ayant la transformation suivante.

Exemple:

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

$('#target_div').html(json2html.transform(data,transform));

pensé que je mettrais
— Chad Brown
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.