Parse JSON Object. Extract subkeys - javascript

I have a JSON file and want to build a table with 2 columns:
{
"Some name 1": {
"price": 1023,
"quantity": 93
},
"Some name 2": {
"price": 2938,
"quantity": 64
},
"Some name 3": {
"price": 1277,
"quantity": 211
}
}
I tried:
$.getJSON('http://localhost:8080/data.json', function (data) {
for (x in data) {
document.getElementById(getTDID).innerHTML += x; // First column
console.log(data[i].price); // Second column
console.log(x["quantity"]); // or another variant of second column
}
}
First column works. But second... I want to extract this 2 values (price and quantity), but it doesn't work. So now I haven't ideas. Please help.

You aren't accessing the values for each key. Try this:
for (const x of Object.keys(data)) {
console.log(data[x]);
}

My mistake was data[x].price instead of data[i].price.

You can try like this
$.getJSON('http://localhost:8080/data.json', function (data) {
for (x in data) {
console.log(data[x].price); // First column
console.log(data[x].quantity); // Second column
}
}

Few observations :
data[i].price should be data[x].price.
x["quantity"] should be data[i].quantity.
Create a TABLE, TR & TD element to display the values in a table.
Working Demo
var jsonObj = {
"Some name 1": {
"price": 1023,
"quantity": 93
},
"Some name 2": {
"price": 2938,
"quantity": 64
},
"Some name 3": {
"price": 1277,
"quantity": 211
}
};
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
document.body.appendChild(x);
for (i in jsonObj) {
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var x = document.createElement("TD");
var nameNode = document.createTextNode(i);
x.appendChild(nameNode);
document.getElementById("myTr").appendChild(x);
var price = document.createElement("TD");
var priceNode = document.createTextNode(jsonObj[i].price);
price.appendChild(priceNode);
document.getElementById("myTr").appendChild(price);
var quantity = document.createElement("TD");
var quantityNode = document.createTextNode(jsonObj[i].quantity);
quantity.appendChild(quantityNode);
document.getElementById("myTr").appendChild(quantity);
}
table, td {
border: 1px solid black;
}

Related

Reading environment variable in javascript

I am trying to achieve something like this.
I am getting a json response after hitting a particular api command (a curl command let's say). I need to convert this result to an html. For this I am thinking of storing the result in an environment variable.
My intentions is to read this variable and so read the json data.
How can I read a environment variable in js?
I am using below program to map the json to html table.
<!DOCTYPE html>
<html>
<head>
<title>Convert JSON Data to HTML Table</title>
<style>
th, td, p, input {
font:14px Verdana;
}
table, th, td
{
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: center;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = [
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
As Quentin says: you can't, but look into Local Storage instead.
JavaScript, running client-side in an HTML document, has no access to environment variables at all. So you can't.

How to extract value from array js

I've already built a table with DOM methods, taking in input the number of row and column. Now I need to take the number of row and column by the element of the array myBooks and put in my table the values of the same array. How should I do?
<!DOCTYPE html>
<html>
<head>
<title>tabella dom</title>
<script type="text/javascript" src="tabellaDom.js"></script>
</head>
<body>
<form name="numeri">
Inserisci due valori: <br>
<input name="valore1">
<input name="valore2">
<br>
<input type="button" name="creaTabella" value="Crea Tabella" onclick="creaTable(numeri.valore1.value, numeri.valore2.value);">
<br>
<div id="myDynamicTable"></div>
</form>
</body>
</html>
function creaTable(a, b) {
var tableDiv = document.getElementById("myDynamicTable");
var tbl = document.createElement('table');
tbl.setAttribute("id", "tabella");
var tbdy = document.createElement('tbody');
tbl.appendChild(tbdy);
tbl.border = '1';
for (var j = 0; j < a; j++) {
const tr = document.createElement('tr');
console.log('tr.value');
tbdy.appendChild(tr);
const btnDelete = document.createElement('input');
btnDelete.setAttribute("type", "button");
btnDelete.setAttribute("value", "-");
tr.appendChild(btnDelete);
btnDelete.onclick = function() {
tr.remove();
};
for (var k = 0; k < b; k++) {
var td = document.createElement('td');
td.width = '75';
td.appendChild(document.createTextNode("Cella " + j + "," + k));
tr.appendChild(td);
}
}
tableDiv.appendChild(tbl);
}
var myBooks = [{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
var data="";
b--;
if(b==0){
data=myBooks[a-1]['Book ID'];
}
else if(b==1){
data=myBooks[a-1]['Book Name'];
}
else if(b==2){
data=myBooks[a-1]['Category'];
}
else if(b==3){
data=myBooks[a-1]['Price'];
}
Try this code. Here a is number of row and b is number of column

Trying to convert the JSON file to an HTML Table using jQuery

I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.
JSON file
[
{
"Book ID": "1",
"Book Name": "Computer Architecture",
"Category": "Computers",
"Price": "125.60"
},
{
"Book ID": "2",
"Book Name": "Asp.Net 4 Blue Book",
"Category": "Programming",
"Price": "56.00"
},
{
"Book ID": "3",
"Book Name": "Popular Science",
"Category": "Science",
"Price": "210.40"
}
]
HTML and JS
<script>
$(document).ready(function () {
$.getJSON("result.json", function (data) {
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
Hi gusy, I am trying to convert the Array to an HTML Table using jQuery. However, the browser shows nothing from the JSON file. Please see my codes below.

HTML,JavaScript, JSON

I have the following json data . How can i show the 'record' values in a html table by using only javascript and html. This json data is a string.
{
"document": {
"record": [
{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-1",
"WForderdate2332532": "2012-06-01T00:00:00+00:00",
"WFregion2332540": "East",
"WFrep2332556": "Jones",
"WFitem2332585": "Pencil",
"WFunits2332555": "95.00",
"WFcost2332532": "1.99",
"WFtotal2332589": "189.05",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
},
{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-2",
"WForderdate2332532": "2012-03-01T00:00:00+00:00",
"WFregion2332540": "Central",
"WFrep2332556": "Kivell",
"WFitem2332585": "Binder",
"WFunits2332555": "50.00",
"WFcost2332532": "19.99",
"WFtotal2332589": "999.50",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
},
]
}
}
To do this you need basically three steps:
convert the string to actual javascript data
find the columns
build the output
1. convert to javascript data
This is easy... just data = JSON.parse(jsonstring);
2. find the columns
If you don't know in advance what are the columns you must iterate over all records to find what are their names. Note that it's possible that different record have different "columns".
var cols = {};
data.document.record.forEach(function(row){
row.forEach(function(col){
cols[col] = 1;
});
});
3. build the output
For this there are two common ways; create the HTML string or create the DOM node elements. The following is using the second method:
var domtable = document.createElement("table");
document.appendChild(domtable);
data.document.record.forEach(function(row){
var domrow = document.createElement("tr");
domtable.appendChild(domrow);
cols.forEach(function(col){
var domcell = document.createElement("td");
domcell.textContent = row[col];
domrow.appendChild(domrow);
});
});
note that if you want to style your elements using CSS to set the class names the code required is for example domcell.className = "cell".
4. ???
...
5. profit
:-)
You can access the 'record' array by :
var records = document.record;
To iterate over the records, you can do:-
for(var index in records) {
var record = records[index];
// Now you can access individual values like record.a
// However your JSON structure seems to be very dynamic so you can also iterate over these keys as well.
for(var key in record) {
var valueForKey = record[key];
// Now you can set this value to specific HTML elment either via jQuery or simple JavaScript depending on your comfort.
}
}
Check this Code:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
</head>
<body>
<div style="width:800px;overflow: auto">
<table id="dataTable" border="1">
</table>
</div>
<script>
var dataString = '{"document":{"record":[{"a":"36a0bb3a1653420fac1ffdbf6f1fc495-1","WForderdate2332532":"2012-06-01T00:00:00+00:00","WFregion2332540":"East","WFrep2332556":"Jones","WFitem2332585":"Pencil","WFunits2332555":"95.00","WFcost2332532":"1.99","WFtotal2332589":"189.05","b":"2014-12-19T05:59:04+00:00","c":"2014-12-19T05:59:05+00:00","d":"pritamb#greencubeglobal.com","e":"pritamb#greencubeglobal.com"},{"a":"36a0bb3a1653420fac1ffdbf6f1fc495-2","WForderdate2332532":"2012-03-01T00:00:00+00:00","WFregion2332540":"Central","WFrep2332556":"Kivell","WFitem2332585":"Binder","WFunits2332555":"50.00","WFcost2332532":"19.99","WFtotal2332589":"999.50","b":"2014-12-19T05:59:04+00:00","c":"2014-12-19T05:59:05+00:00","d":"pritamb#greencubeglobal.com","e":"pritamb#greencubeglobal.com"}]}}';
function createTable() {
var dataObj = JSON.parse(dataString);
var records = dataObj["document"]["record"];
var rowString = "";
var headRow = "<tr>";
var headObj = records[0];
for (var key in headObj) {
headRow += "<th>" + key + "</th>";
}
headRow += "</tr>";
for (var key in records) {
rowString += '<tr>';
var obj = records[key];
var tdString = "";
for (var key1 in obj) {
tdString += "<td>" + obj[key1] + "</td>";
}
rowString += tdString;
rowString += "</tr>";
}
rowString = headRow + rowString;
$("#dataTable").html(rowString);
}
createTable();
</script>
</body>
</html>
var myjson = {
"document": {
"record": [{
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-1",
"WForderdate2332532": "2012-06-01T00:00:00+00:00",
"WFregion2332540": "East",
"WFrep2332556": "Jones",
"WFitem2332585": "Pencil",
"WFunits2332555": "95.00",
"WFcost2332532": "1.99",
"WFtotal2332589": "189.05",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
}, {
"a": "36a0bb3a1653420fac1ffdbf6f1fc495-2",
"WForderdate2332532": "2012-03-01T00:00:00+00:00",
"WFregion2332540": "Central",
"WFrep2332556": "Kivell",
"WFitem2332585": "Binder",
"WFunits2332555": "50.00",
"WFcost2332532": "19.99",
"WFtotal2332589": "999.50",
"b": "2014-12-19T05:59:04+00:00",
"c": "2014-12-19T05:59:05+00:00",
"d": "pritamb#greencubeglobal.com",
"e": "pritamb#greencubeglobal.com"
}, ]
}
};
var records = myjson.document.record;
var table = document.getElementsByTagName("table")[0]
//console.log(table.tHead.rows[0])
//console.log(table);
for (var key in records[0]) {
th = document.createElement("th");
th.appendChild(document.createTextNode(key))
table.tHead.rows[0].appendChild(th);
}
for (i = 0; i < records.length; i++) {
tr = table.getElementsByTagName("tbody")[0].insertRow(i)
for (var key in records[0]) {
td = document.createElement("td")
td.appendChild(document.createTextNode(records[i][key]))
tr.appendChild(td);
}
}
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>

Create table using Javascript from JSON [duplicate]

This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 8 years ago.
I have data in an object that I'm trying to display in a table. Unfortunately, all my columns are displaying undefined.
var fifadata = [{
"fields": ["id", "country", "alternate_name", "fifa_code", "group_id", "group_letter", "wins", "draws", "losses", "games_played", "points", "goals_for", "goals_against", "goal_differential"]
}, {
"id": 1,
"country": "Brazil",
"alternate_name": null,
"fifa_code": "BRA",
"group_id": 1,
"group_letter": "A",
"wins": 4,
"draws": 1,
"losses": 2,
"games_played": 7,
"points": 13,
"goals_for": 11,
"goals_against": 14,
"goal_differential": -3
}, {
"id": 2,
"country": "Croatia",
"alternate_name": null,
"fifa_code": "CRO",
"group_id": 1,
"group_letter": "A",
"wins": 1,
"draws": 0,
"losses": 2,
"games_played": 3,
"points": 3,
"goals_for": 6,
"goals_against": 6,
"goal_differential": 0
}, {
"id": 3,
"country": "Mexico",
"alternate_name": null,
"fifa_code": "MEX",
"group_id": 1,
"group_letter": "A",
"wins": 2,
"draws": 1,
"losses": 1,
"games_played": 4,
"points": 7,
"goals_for": 5,
"goals_against": 3,
"goal_differential": 2
}];
var body = document.getElementsByTagName('body')[0];
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var th = document.createElement("th");
var caption = document.createElement('caption');
var cap = document.createTextNode("Game Results List");
caption.appendChild(cap);
caption.style.fontWeight = "900";
table.appendChild(caption);
body.appendChild(table);
table.style.border = "1px dashed red";
table.style.borderSpacing = "1px";
table.style.textAlign = "center";
//table head(correct)
for (i = 0; i < 1; i++) {
var tr = document.createElement("tr");
thead.appendChild(tr);
table.appendChild(thead);
for (j = 0; j < fifadata[0].fields.length; j++) {
var th = document.createElement("th");
var keyname = fifadata[0].fields[j];
var tm = document.createTextNode(keyname);
th.appendChild(tm);
tr.appendChild(th);
th.style.border = "1px dashed blue";
th.style.padding = "5px";
}
}
//table body(incorrect).
//I need to use a dynamically created property(i.e. keyinfo) in "var text"
//i.e.fifadata[i].keyinfo; should change into fifadata[1].ID when it is
//excecuted.
for (i = 1; i < fifadata.length; i++) {
var tr = document.createElement("tr");
tbody.appendChild(tr);
table.appendChild(tbody);
for (j = 0; j < fifadata[0].fields.length; j++) {
var td = document.createElement("td");
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo;
var tn = document.createTextNode(test);
td.appendChild(tn);
tr.appendChild(td);
td.style.border = "1px dashed green";
td.style.padding = "2px";
}
}
If all goes well it should create a table from the JSON data. Can my code be modified slightly? Is there an easier why to do it?
You can't use variables like that in dot notation. You're essentially asking for a property named keyinfo, which doesn't exist.
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i].keyinfo; // wrong
To access the property whose name is keyinfo's value, you'll need to use bracket notation, like so:
var keyinfo = fifadata[0].fields[j];
var test = fifadata[i][keyinfo]; // right
Have a look at this simplified demo:
(function() {
// loading data from a hidden input to declutter the demo script
var fifadata = JSON.parse(document.getElementById("fifadata").value);
var table = document.createElement("table");
var thead = table.appendChild(document.createElement("thead"));
var tbody = table.appendChild(document.createElement("tbody"));
var row = thead.insertRow(-1);
// remove the first item in fifadata and get a reference to its fields property
var fieldNames = fifadata.shift().fields;
// create column headers
fieldNames.forEach(function(fieldName) {
row.appendChild(document.createElement("th")).textContent = fieldName;
});
// populate tbody rows
fifadata.forEach(function(record) {
row = tbody.insertRow(-1);
fieldNames.forEach(function(fieldName) {
// note that we use bracket notation to access the property
row.insertCell(-1).textContent = record[fieldName];
});
});
// add the table to the body once fully constructed
document.body.appendChild(table);
})();
<input type="hidden" id="fifadata" value='[{"fields":["id","country","alternate_name","fifa_code","group_id","group_letter","wins","draws","losses","games_played","points","goals_for","goals_against","goal_differential"]},{"id":1,"country":"Brazil","alternate_name":null,"fifa_code":"BRA","group_id":1,"group_letter":"A","wins":4,"draws":1,"losses":2,"games_played":7,"points":13,"goals_for":11,"goals_against":14,"goal_differential":-3},{"id":2,"country":"Croatia","alternate_name":null,"fifa_code":"CRO","group_id":1,"group_letter":"A","wins":1,"draws":0,"losses":2,"games_played":3,"points":3,"goals_for":6,"goals_against":6,"goal_differential":0},{"id":3,"country":"Mexico","alternate_name":null,"fifa_code":"MEX","group_id":1,"group_letter":"A","wins":2,"draws":1,"losses":1,"games_played":4,"points":7,"goals_for":5,"goals_against":3,"goal_differential":2}]'/>
See also: Property Accessors, Array.prototype.forEach(), Array.prototype.shift(), HTMLTableElement.insertRow(), HTMLTableRowElement.insertCell(), and Node.textContent

Categories