admin管理员组文章数量:1221303
First time being exposed to JSON so please explain like I'm 5 without the jargon. I have been given a JSON file like this and need to display these items in a list in HTML. A lot of examples have the JSON object assigned to a variable- this isn't assigned to a variable so I'm unsure how to reference it. How can I access and display everything in product list. In my html I have linked to a script.js file and also this json file.
HTML
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
JSON
"basket": {
"productList": [{
"product": {
"id": "111",
"name": "Dog",
"shortDescription": "<p>Mans best friend</p>",
},
"category": "Canine",
"availability": "In Stock",
"variationType": {
"name": "Breed",
"value": "Collie"
}
},
"quantity": 1,
"price": "$53.00"
}, {
"product": {
"id": "112",
"name": "Dog",
"shortDescription": "<p>Not so best friend</p>",
"category": "feline",
"availability": "Low In Stock",
"variationType": {
"name": "breed",
"value": "Maine Coon"
}
},
"quantity": 1,
"price": "$49.00"
}, {
"product": {
"id": "113",
"name": "Rabbit",
"shortDescription": "Likes carrots",
"category": "cuniculus",
"availability": "In Stock"
},
"quantity": 1,
"price": "$66.00"
}]
}
JavaScript
var products = document.getElementById("cartItemsList");
cartItemsList.innerHTML = "<li>" + product + "</li>";
First time being exposed to JSON so please explain like I'm 5 without the jargon. I have been given a JSON file like this and need to display these items in a list in HTML. A lot of examples have the JSON object assigned to a variable- this isn't assigned to a variable so I'm unsure how to reference it. How can I access and display everything in product list. In my html I have linked to a script.js file and also this json file.
HTML
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
JSON
"basket": {
"productList": [{
"product": {
"id": "111",
"name": "Dog",
"shortDescription": "<p>Mans best friend</p>",
},
"category": "Canine",
"availability": "In Stock",
"variationType": {
"name": "Breed",
"value": "Collie"
}
},
"quantity": 1,
"price": "$53.00"
}, {
"product": {
"id": "112",
"name": "Dog",
"shortDescription": "<p>Not so best friend</p>",
"category": "feline",
"availability": "Low In Stock",
"variationType": {
"name": "breed",
"value": "Maine Coon"
}
},
"quantity": 1,
"price": "$49.00"
}, {
"product": {
"id": "113",
"name": "Rabbit",
"shortDescription": "Likes carrots",
"category": "cuniculus",
"availability": "In Stock"
},
"quantity": 1,
"price": "$66.00"
}]
}
JavaScript
var products = document.getElementById("cartItemsList");
cartItemsList.innerHTML = "<li>" + product + "</li>";
Share
Improve this question
asked Dec 16, 2017 at 23:43
DumbDevGirl42069DumbDevGirl42069
9595 gold badges24 silver badges54 bronze badges
1
- Can you also add the code you use to get the json from your server? I have a feeling this resource would help you: developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started – Rob Monhemius Commented Dec 17, 2017 at 16:14
5 Answers
Reset to default 6If you are loading this from an external file, you will need Ajax or a similar type of call. To use Ajax, you'll have to add a library called jQuery to your project's HTML file. Then you can call your JSON without referencing it as a javascript variable as you see in the following working code snippet.
/* I put your JSON into an external file, loaded from github */
var url = "https://raw.githubusercontent.com/mspanish/playground/master/jessica.json";
/* this tells the page to wait until jQuery has loaded, so you can use the Ajax call */
$(document).ready(function(){
$.ajax({
url: url,
dataType: 'json',
error: function(){
console.log('JSON FAILED for data');
},
success:function(results){
/* the results is your json, you can reference the elements directly by using it here, without creating any additional variables */
var cartItemsList = document.getElementById("cartItemsList");
results.basket.productList.forEach(function(element) {
cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
}); // end of forEach
} // end of success fn
}) // end of Ajax call
}) // end of $(document).ready() function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
if you want to parse an object:
function logTheObj(obj) {
var ret = "";
for (var o in obj) {
var data = obj[o];
if (typeof data !== 'object') {
ret += "<li>" + o + " : " + data + "</li>";
} else {
ret += "<li>" + o + " : " + logTheObj(data) + "</li>";
}
}
return "<ul>" + ret + "</ul>";
}
If your object is in a string:
logTheObj(JSON.parse(jsonString));
Unless you use an Ajax call or something similar to load external JSON, you need to convert the JSON you've provided into an object that you can reference as a variable. Also, your JSON is not valid. I tried correcting it here, and am going to reference your JSON as an object you can reference via a variable named obj. Here is a working code snippet.
var obj = {
"basket": {
"productList": [{
"product": {
"id": "111",
"name": "Dog",
"shortDescription": "<p>Mans best friend</p>",
"category": "Canine",
"availability": "In Stock",
"variationType": {
"name": "Breed",
"value": "Collie"
}
},
"quantity": 1,
"price": "$53.00"
}, {
"product": {
"id": "112",
"name": "Dog",
"shortDescription": "<p>Not so best friend</p>",
"category": "feline",
"availability": "Low In Stock",
"variationType": {
"name": "breed",
"value": "Maine Coon"
}
},
"quantity": 1,
"price": "$49.00"
}, {
"product": {
"id": "113",
"name": "Rabbit",
"shortDescription": "Likes carrots",
"category": "cuniculus",
"availability": "In Stock"
},
"quantity": 1,
"price": "$66.00"
}]
}
}
var cartItemsList = document.getElementById("cartItemsList");
obj.basket.productList.forEach(function(element) {
cartItemsList.insertAdjacentHTML( 'beforeend',"<li>" + element.product.name + " : " + element.price+ " </li>");
});
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
JavaScript version using external json file from previous answer by Stacey Reiman
const products = document.getElementById("cartItemsList");
/* get basket items from JSON */
class Basket {
async cartItems() {
try {
let result = await fetch('https://raw.githubusercontent.com/mspanish/playground/master/jessica.json')
let data = await result.json()
// return data
/* destructuring data */
let basketItems = data.basket.productList
basketItems = basketItems.map(item =>{
const price = item.price
const{id,name,shortDescription,category,availability} = item.product
const breed = item.product.variationType
const quantity = item.quantity
return {price,id,name,shortDescription,category,availability,quantity,breed}
})
return basketItems
} catch (error) {
console.log(error)
}
}
}
/* Display stuff from the basket */
class Display {
displayBasket(basket) {
//console.log(basket)
let result = ""
basket.forEach((item)=>{
result += `
<li>
id : ${item.id}
name: ${item.name}
price: ${item.price}
availability: ${item.availability}
category : ${item.category}
quantity : ${item.quantity}
shortDescription : ${item.shortDescription}
</li>
`})
cartItemsList.innerHTML = result
}
}
document.addEventListener("DOMContentLoaded", ()=>{
const basket = new Basket()
const display = new Display()
basket.cartItems().then(basket => display.displayBasket(basket))
})
<h1>My Cart</h1>
<div id="cart">
<h2>Cart Items</h2>
<ul id="cartItemsList">
</ul>
</div>
First, you have to convert the json
from long string to acutely js object.
you doing so by the JSON.parse
command. like so:
let jsObj = JSON.parse( youreJsonString);
Them, you can loop throw youre products in your productList and build your html code, like so:
var products = document.getElementById("cartItemsList");
jsObj.basket.productList.forEach( function(product ) {
cartItemsList.innerHTML = "<li>" + product.name + " : " + product.price+ " </li>";
});
本文标签: Display JSON data to HTML page using JavaScriptStack Overflow
版权声明:本文标题:Display JSON data to HTML page using JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739342796a2159015.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论