I have problem when i want to get a value from json
const data = {
"first_name": "Sammy",
"last_name": "Shark",
"location": "Ocean",
"websites": [{
"description": "work",
"URL": "https://www.digitalocean.com/"
}, {
"desciption": "tutorials",
"URL": "https://www.digitalocean.com/community/tutorials"
}],
"social_media": [{
"description": "twitter",
"link": "https://twitter.com/digitalocean"
}, {
"description": "facebook",
"link": "https://www.facebook.com/DigitalOceanCloudHosting"
}, {
"description": "github",
"link": "https://github.com/digitalocean"
}]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var dataTarget = "https://tech/json-data.php";
$.getJSON(dataTarget, function(data) {
var output;
output += `<tr>
<th scope="col">name</th>
<th scope="col">description</th>
<tbody>`
$.each(data, function(key, val) {
output += '<tr>';
output += '<td>' + val.websites.description + '<td>';
output += '</tr>';
output += '</tbody>';
});
$('table').html(output);
});
</script>
but it showing an error code "Uncaught TypeError: Cannot read property 'description' of undefined"
if you only need websites decription, use data.websites for $.each() parameter, because from data you need second loop/each
var data = {
"first_name": "Sammy",
"last_name": "Shark",
"location": "Ocean",
"websites": [{
"description": "work",
"URL": "https://www.digitalocean.com/"
},
{
"description": "tutorials",
"URL": "https://www.digitalocean.com/community/tutorials"
}
],
"social_media": [{
"description": "twitter",
"link": "https://twitter.com/digitalocean"
},
{
"description": "facebook",
"link": "https://www.facebook.com/DigitalOceanCloudHosting"
},
{
"description": "github",
"link": "https://github.com/digitalocean"
}
]
}
var output = ''
$.each(data.websites, function(key, val) {
output += '<tr><td>' + val.description + '</td></tr>';
});
//console.log(output)
$('table').html(output);
<table></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It is throwing an error because the "websites" key is an array, instead you should access the array element by referring to it's index number like this:
output += "<td>" + val.websites[0].description + "<td>";
Related
With push of a button there should be a html that contains info from json, but nothing happens.
When i used console.log to show the whole JSON info, it worked. BUt when added table and and only specific arrays, it does nothing. There are no errors.
<button type="button" id="nappi">paina</button>
<table id="taulu">
<tr>
<th>manufacturer</th>
<th>model</th>
<th>price</th>
<th>wiki</th>
</tr>
</table>
var nappi = document.getElementById("nappi");
nappi.addEventListener("click", function(){
$(document).ready(function(){
$.getJSON("./cars.json", function(data){
var tiedot = '';
$.each(data, function(key, value){
tiedot += '<tr>';
tiedot += '<td>'+value.manufacturer+'</td>';
tiedot += '<td>'+value.model+'</td>';
tiedot += '<td>'+value.price+'</td>';
tiedot += '<td>'+value.wiki+'</td>';
tiedot += '</tr>';
});
$('taulu').append(tiedot);
});
});
});
{
"data": [{
"manufacturer": "Porsche",
"model": "911",
"price": 135000,
"quality": [{
"name": "overall",
"rating": 3
}, {
"name": "mechanical",
"rating": 4
}, {
"name": "powertrain",
"rating": 2
}, {
"name": "body",
"rating": 4
}, {
"name": "interior",
"rating": 3
}, {
"name": "accessories",
"rating": 2
}],
"wiki": "http://en.wikipedia.org/wiki/Porsche_997"
}]
}
You forgot # before the ID. $(' > # < taulu ') $('#taulu')
I'm trying to get a certain value from a Json file for html injection. The Json can have multiple arrays much more than in this example, but only the first array value of each array has certain value called title. Example json:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
I'm inserting all the values to HTML in a function that loops trough all of the arrays in the object. Here the problem is that I don't know how to insert the title value so that the HTML gets it. Tried numerous ways doing it but all failed. I'm trying to insert the title value at toimipistedata[key1][0].title:
function CreateAccordionTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
placesdata[key1][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + Object.keys(placesdata)[i] + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}
}
(The $container is an id/class for HTML element)
So how can I get the title value from the object arrays so that I can insert it with the HTML?
Tried to make a snippet about how it currently works and what needs to be changed in comments but failed something so it broke:
var placesdata= {
"Places": {
"Berlin": [
{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [
{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
function CreateTitles($container) {
for (var i = 0; i < Object.keys(placesdata).length; i++) {
var component =
'<li>' +
Object.keys(placesdata)[i] + //this needs to get the title value like this toimipistedata[key1][0].title
'<ul class="place ' + Object.keys(placesdata)[i] + '\">' +
'</ul>' +
'</li>'
if ($container.length) {
$container.append(component);
//CreateToimipisteContent(placesdata.Object.keys(placesdataa)[i], "." + Object.keys(placesdata)[i]); I need this to work
}
}
}
function CreateToimipisteContent(data, elementpos) {
for (var i = 0; i < data.length; i++) {
var dat = data;
var $txtp = $('<li>' + dat[i].location + '</li>').appendTo(elementpos);
$txtp.addClass(dat[i].buildings);
}
}
CreateTitles($("#Placement"));
CreateToimipisteContent(placesdata.Poliklinikat, ".Berlin"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
CreateToimipisteContent(placesdata.Tutkimustoimenpiteet, ".Paris"); // i dont want to use these like this they need to come form the CreateTitles function, these should be removed
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="Placement"></ul>
<script src="jquery-3.3.1.min.js"></script>
</body>
</html>
You could use Array.prototype.find, which returns the first element that fulfils the supplied predicate.
I've got no idea what toimipistedata is so I'll give you as close an example as I can:
var title = placesdata.Places[city].find(x => x.title).title;
This works because any element in the placesdata.Places[city] array that has the title property set will be "truthy", so that object will be returned.
Just to expand on #ChristianScott's answer a bit, you could loop over placesdata["Places"] to get the city, and then use the find method to get the title.
So, for completeness:
var placesdata = {
"Places": {
"Berlin": [{
"location": "Center",
"buildings": "A",
"title": "Germany"
},
{
"location": "Suburbs",
"buildings": "B",
}
],
"Paris": [{
"location": "Center",
"buildings": "C",
"title": "France"
},
{
"location": "Suburbs",
"buildings": "D",
},
{
"location": "Outskirts",
"buildings": "E",
}
]
}
}
let titles = []; // titles array
for (let city in placesdata["Places"]) { // for each city
titles.push(placesdata.Places[city].find(x => x.title).title); // find & push title
}
console.log(titles);
You can try this simple solution using for in:
var places = placesdata.Places;
for (var place in places) {
var component =
'<div class="title">' +
'<i class="dropdown icon"></i>' +
places[place][0].title +
'</div>' +
'<div class="content styleSetSubAccordion">' +
'<div class="ui two column divided grid ' + place + '\">' +
'</div>' +
'</div>'
if ($container.length) {
$container.append(component);
}
}
I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
Guys
I want to read from json file ,i create json file and use ajax to read from it.
i create Video object which contain Courses objects (title & URL)
.
i try to read title & url of HTML as Example but no data show in the HTML page .
{
"video": {
"HTML": [
{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
},
{
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
},
{
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
},
{
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [
{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
},
{
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
},
{
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
},
{
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}
],
"JavaScript": [
{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
},
{
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
},
{
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
},
{
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
},
{
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
},
{
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
},
{
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}
],
"Jquery": [
{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
},
{
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
},
{
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
},
{
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}
]
}
}
i use ajax to read from it , i need to read all HTML titles and URLs . what is the wrong with this ?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="id01"></div>
<script>
var xhr;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', 'video.json');
xhr.onreadystatechange = function ()
{
if ((xhr.readyState === 4) && (xhr.status === 200)) {
var arr = JSON.parse(xhr.responseText);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
video[HTML][i].title +
"</td><td>" +
video[HTML][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
}
xhr.send();
</script>
</body>
</html>
Try substituting video["HTML"][i].title where "HTML" is string for HTML at video[HTML][i].title , also arr is not an array, but an object
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
var json = {
"video": {
"HTML": [{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
}, {
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
}, {
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
}, {
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
}, {
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
}, {
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
}, {
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}],
"JavaScript": [{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
}, {
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
}, {
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
}, {
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
}, {
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
}, {
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
}, {
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}],
"Jquery": [{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
}, {
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
}, {
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
}, {
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}]
}
};
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.body.innerHTML = out;
This
video[HTML][i].title
Should be
video.html[i].title
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to display data received as Ajax callback in my app's page. The data somewhat looks like this:
"data": [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
The API contain more than 100 data, so how can we display these data in a html page. like this:
Name: Rehan
location: Pune
Description: hello hi
created by: 13692
user name: xyz
Edit
Alternatively, as suggested in comments / solutions, how to display the data as an HTML table?
You can use for to loop thru the array and contruct an HTML string. Use jQuery's .append() to add the string to the body.
var data = [{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
]
var htmlText = '';
for (var key in data) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].name + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
.div-conatiner {
background-color: #eeeeee;
margin-bottom: 5px;
padding: 5px;
}
.div-conatiner p {
margin : 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
UPDATE: Another option is using map to loop thru the array and use Template literals to construct the HTML
var data = [{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
},
]
var htmlText = data.map(function(o){
return `
<div class="div-conatiner">
<p class="p-name"> Name: ${o.name}</p>
<p class="p-loc"> Location: ${o.location}</p>
<p class="p-desc"> Description: ${o.description}</p>
<p class="p-created"> Created by: ${o.created_by}</p>
<p class="p-uname"> Username: ${o.users_name}</p>
</div>
`;
});
$('body').append(htmlText);
.div-conatiner {
background-color: #eeeeee;
margin-bottom: 5px;
padding: 5px;
}
.div-conatiner p {
margin: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this:
<div id="json"></div>
<script>
var obj = {"data": [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
}
]}
var divId = document.getElementById("json")
for(var i=0;i<obj.data.length;i++)
for(var keys in obj.data[i]){
console.log(keys +"-->"+obj.data[i][keys]);
divId.innerHTML = divId.innerHTML + "<br/>"+ keys +"-->"+obj.data[i][keys];
}
</script>
Fiddle : http://jsfiddle.net/Sourabh_/1m2tjth3/
You can modify this as per your requirement.
Assuming you have a table with id #table, loop through the json object and append a row for every object item:
var jsonObj = { ... }
for (i in jsonObj) {
for (n in jsonObj[i]) {
$('#table > tbody').append('<tr><th>' + n + '</th><td>' + jsonObj[i][n] + '</td></tr>');
}
}
var data = [
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"users_name": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"users_name": "abc",
}];
for (i=0;i<=data.length;i++) {
for (n in data[i]) {
$('#table > tbody').append('<tr><th>' + n + '</th><td>' + data[i][n] + '</td></tr>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table">
<tbody>
</tbody>
</table>