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'], 
  ]
2
  • you could always convert the json to a normal array then append the dat you want and then convert it back to json Commented May 30, 2019 at 9: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"]... Commented Jun 1, 2019 at 5:51

2 Answers 2

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)
    }
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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)
I tried 'console.log(json["hits"]["hits"])' and the result is the correct json that I want.
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.
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>

2 Comments

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 I have edited my answer to include your new JSON structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.