Alloys
Alloys

Reputation: 175

Dynamically Render Unstrutured JSON Data in an html Table

I have some data that is available in json, in this format

"card": {
  "id": "ybLaK64d",
  "type": "VISA",
  "last4": "1881",
  "expMonth": 11,
  "expYear": 17,
  "dateCreated": 1429515587898,
  "cardEntryMode": "E_COMMERCE"
},
"disputed": false,
"amount": 1000,
"settlementAmount": 1000,
"tagPurchase":true, //optional  

the card object structure is fixed, but there could be up to 10 extra optional fields. I want to render this in an html table dynamically, such that rows with missing fields are marked undefined. my front end is angularjs, pulling in the json via $http. my final table would be something like this

<table>
  <thead>
    <tr>
      <td>card.id</td>
      <td>card.type</td>
      .
      .
      .
     <td>card.cardentrymode</td>
     <td>disputed</td>
     <td>amount</td>
    </tr>
  </thead>
  <tbody>
      .
      .
      .
  </tbody>
<table>

how can I get this done, so that the table is dynamically created, is updated in real time and so that the table headers are created from the record with the most optional fields?

Upvotes: 0

Views: 523

Answers (1)

datamosh
datamosh

Reputation: 130

I had a similar issue in the past.

My solution included having a table with all the possible columns. Otherwise a really bad UX will result from an ever-changing column name.

So you must know in advance the name of ALL the fields you want to display.

At first load of the data you fill an object that follows YOUR desired structure, assigning "N/A" for missing data.

Then, each time a new set of data is fetched, you update your own object with the new data.

As Enzey pointed out in his comment, it's not easy. And changing the column name doesn't really help consuming the data, which is the end goal of a table! :)

Upvotes: 1

Related Questions