0

I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?

Json file:

{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }

My code:

    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]         
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }

Edit: Add expected output: change the json file to the following structure.

[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'], 
  ]
Avi Meltser
  • 409
  • 4
  • 11
landy
  • 29
  • 1
  • 7
  • you could always convert the json to a normal array then append the dat you want and then convert it back to json – Sir Catzilla May 30 '19 at 09:27
  • Please explain what this part is supposed to be and how it pertains to the rest of the code? `"v": json["hits"]["hits"][i]["_source"]...` – zer00ne Jun 01 '19 at 05:51

2 Answers2

1

I guess you need push (Or concat / push(...elements) if you want to add array of rows)

    jdata.rows = [];
    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]         
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.push(row);
        // for elements from row
        // jdata.rows.push(...row)
    }
Krzysiek
  • 2,494
  • 16
  • 20
  • Thank you for your help. 'push' is a nice way. but I get error 'Cannot read property '0' of undefined' back. Did I misunderstand array and json data? – landy May 31 '19 at 09:03
  • Which line is that? In this code only thing I can see with numeric index is `json["hits"]["hits"][i]`. Try to `console.log(json["hits"])` and check values in element's inspector console (proly `ctrl+shift+i`) – Krzysiek May 31 '19 at 22:34
  • I tried 'console.log(json["hits"]["hits"])' and the result is the correct json that I want. – landy Jun 04 '19 at 13:07
  • I find the problem of 'Cannot read property '0' of undefined'. remove one bracket in the code: row = [ { "c":...} ] => row = {"c"...}. It works nice now. Thanks again. – landy Jun 04 '19 at 13:37
1

There are a few errors in your code

  1. The JSON needs to be an array so you can loop through each object to display.
  2. insertRow() is a method from the Table object, jdata.rows is not a Table object but an array.

Since, you have used insertRow(), I have rewritten your code to display the table data using the Table Object methods. Here is a code snippet

Edit: You can use the push() method to create your required JSON structure. I have edited the code snippet to create your required JSON.

var jdata = {
  cols: [{
      "id": "1",
      "label": "name",
      "type": "string"
    },
    {
      "id": "2",
      "label": "country",
      "type": "string"
    }
  ],
  rows: []
};

var persons = [{
    "name": "lily",
    "country": "china",
    "age": 23
  },
  {
    "name": "mike",
    "country": "japan",
    "age": 22
  }, {
    "name": "lucy",
    "country": "korea",
    "age": 25
  }
];

var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);

jdata.cols.forEach((col, index) => {
  var cell = rowHeader.insertCell(index);
  cell.innerHTML = col.label;
});

persons.forEach((person, index) => {
  var rowFooter = footer.insertRow(index);
  rowFooter.insertCell(0).innerHTML = person.name;
  rowFooter.insertCell(1).innerHTML = person.country;
  
  jdata.rows.push([person.name, person.country]);
});

console.log(jdata.rows);
<table id="table">

</table>
nash11
  • 8,220
  • 3
  • 19
  • 55
  • Thank you for the clear comment! but I don't want the table showed on the web. I want to transfer the json file to the new structure(edited). – landy May 31 '19 at 09:19
  • @landy I have edited my answer to include your new JSON structure. – nash11 May 31 '19 at 09:48