-2

I am a newbie here in JSON and need your input. I have a html file which loads my .json file

  <script type="text/javascript">
    function load_data() {
      $.getJSON("/data/rain.json", function(data) {
.....
       });
   }
   load_data();

where my rain.json file is loading the counts of raining days in the last month (30 days), quarterly and yearly

{
   "30 days": 1,
   "90 days": 17,
   "365 days": 80,
   "last_update": "2019-11-11 17:07:33"
}

How to I display this information in one row of the table with the header?

Thanks.

user1360367
  • 37
  • 1
  • 3
  • Welcome to Stack Overflow! This is not a website where people write code for you so that you don't have to. If you need help debugging code that you have written, you must post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and explain the specific problem with your code. – Giovani Vercauteren Dec 11 '19 at 12:36
  • [Here's](https://stackoverflow.com/a/11480797/2174170) a possible solution that might help you – Dumisani Dec 11 '19 at 12:40
  • Does this answer your question? [Convert json data to a html table](https://stackoverflow.com/questions/5180382/convert-json-data-to-a-html-table) – tevemadar Dec 11 '19 at 12:54

2 Answers2

0

You can iterate through object entries to create columns and then add those to some table. Here is a pseudocode:

const [th, tr] = Object.entries(object).reduce(
  ([ th, tr ], [ key, value ]) => {
    addTd(th, createTd(key));
    addTd(tr, createTd(value));

    return [ th, tr ];
  }, [ createTh(), createTr() ]
)

addRow(table, th);
addRow(table, tr);

You just need to implement createTh(), createTr(), createTd(), addTd() and addRow() functions =)

Andres
  • 967
  • 6
  • 7
0

You can do this with Object#entries, Array#map, Destructuring and Template LIterals

The idea is to transform your data into an array which is easier to parse and keeps things dynamic.

i.e.:

const data = {
   "30 days": 1,
   "90 days": 17,
   "365 days": 80,
   "last_update": "2019-11-11 17:07:33"
};

console.log(Object.entries(data));

Then when you have an array (from your data) you can map through it and build your table.

Solution:

const data = {
   "30 days": 1,
   "90 days": 17,
   "365 days": 80,
   "last_update": "2019-11-11 17:07:33"
};

const entries = Object.entries(data);

document.body.innerHTML = `
  <table>
    <tr>
      ${entries.map(([key])=>`<th>${key}</th>`).join("")}
    </tr>
    <tr>
      ${entries.map(([,value])=>`<td>${value}</td>`).join("")}
    </tr>
  </table>
`
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
  • I have a python script that dump the above { 30 days ...}.I am trying to generate the similar output as you shown earlier in the html inside the – user1360367 Dec 11 '19 at 13:28