skip to Main Content

Hello I am new to JavaScript and I have been trying to parse JSON data into a JavaScript array. I can load the local .json file and print it to the console. I want to print each ‘key’ and ‘value’ pair. Having come from a python background, this is new to me. This is a sample JSON data. The structure of the data I want to use is the same. I am mostly having trouble because of the strucure of the JSON data. I have to control to change the structure of the JSON data

{
    "emp_details":[
    {
        "emp_name":["abc"],
        "email":["[email protected]"],
        "job_profile":["Full time"]
    }
    
    ]
}

And here is what I have done. Which is just read the local file and print it to the console.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

readTextFile("./data.json",function(text){
    var data = JSON.parse(text);
    var dataArray = []
    dataArray.push(data)    
    //alert(data);
    console.log(dataArray[0]);
});

Ideally I want the result to be like to display in an HTML table:

emp_name email job_profile
abc [email protected] Full time

Thank you!

3

Answers


  1. You can use console.table to print tabular data.

    let data = {
      "emp_details": [
        {
          "emp_name": ["abc"],
          "email": ["[email protected]"],
          "job_profile": ["Full time"]
        },
        {
          "emp_name": ["def"],
          "email": ["[email protected]"],
          "job_profile": ["Full time"]
        }
      ]
    }
    
    // convert the array in each property to a string
    let emp_details = data["emp_details"].map(function(employee) {
      return {
        emp_name: employee.emp_name[0],
        email: employee.email[0],
        job_profile: employee.job_profile[0],
      }
    });
    
    // print the data in a table
    console.table(emp_details)
    
    Login or Signup to reply.
  2. You could create a table in your html file with an id of table:

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

    And then use a nested for loop to iterate through the data by doing something like this:

    readTextFile("./data.json", function(text) {
        var data = JSON.parse(text);
        var dataArray = data.emp_details;
        var table = document.getElementById("table");
    
        for (var i = 0; i < dataArray.length; i++) {
            var row = table.insertRow();
    
            for (var key in dataArray[i]) {
                var cell1 = row.insertCell();
                var cell2 = row.insertCell();
    
                cell1.innerHTML = key;
                cell2.innerHTML = dataArray[i][key];
            }
        }
    });
    

    The first for loop iterates through the emp_details array, and the second for loop iterates through each object in the array.

    The key and value of each object is then inserted into a new row in the table, with the key in the first cell and the value in the second cell.

    Login or Signup to reply.
  3. I am assuming that you already have defined HTML table named emp_table, so in that case, you can get desired output by following code: –

    const empTable = document.getElementById('emp_table');
    
    empTable.innerHTML = json.emp_details.map((emp) =>
      Object.keys(emp).map(
        (key) =>
          `<tr><td><label><strong>${key}</strong><label></td><td>${emp[key][0]}</td></tr>`
      )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search