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 | job_profile | |
---|---|---|
abc | [email protected] | Full time |
Thank you!
3
Answers
You can use console.table to print tabular data.
You could create a table in your html file with an id of table:
And then use a nested for loop to iterate through the data by doing something like this:
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.
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: –