Create table from json to javascript using jquery for any field
I can still view the json response. Now I wanted to convert them to tables. I am using the following code to parse city weather data. I am trying to use the following code.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
);}
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
</script>
</head>
<body>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>
</body>
</html>
I got the following result:
And in chrome I can't even see that
+3
user4993723
source
to share
1 answer
The answer I get is an object, not an array. Treat the response as an object.
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
myList = JSON.parse(myList);
console.log(myList);
var keys = [];
for (var key in myList) {
keys.push(key);
}
addAllColumnHeaders(myList, keys);
var row$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var cellValue = myList[key];
if (cellValue == null) {
cellValue = "";
} else if (typeof cellValue == "object") {
cellValue = JSON.stringify(cellValue);
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
});
}
function addAllColumnHeaders(myList, keys) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
headerTr$.append($('<th/>').html(key));
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>
+1
source to share