如何从我的JSON字符串中提取商品和价格?我只能提价...当我在console.log中它显示我想要的东西,但是当我做一个innerHTML时,它不起作用。我需要一个for循环吗?请帮忙,谢谢
<html>
<p id="demo">
</p>
<script>
var myJSON = '{"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"}, "drinks": { "soda": { "small": "1.95", "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.menu.toppings.pepperoni;
document.getElementById("demo").innerHTML = myObj.menu.toppings;
console.log(myObj.menu.toppings);
/*for (var i; i< myObj.length; i++){
console.log(i);
};*/
</script>
</html>
答案 0 :(得分:0)
首先,我建议你使用textContent
,而不是innerHTML
来做这样的事情。
其次,您必须将对象myObj.menu.toppings
转换为字符串,而不是直接将其用作对象。如何将对象转换为字符串取决于您希望如何格式化。
可行的快捷方式(但可能不是您想要的格式)是JSON.stringify(myObj.menu.toppings)
。
答案 1 :(得分:0)
JSON.stringify(...)
字符串化对象。innerText
来改善格式。
var myJSON = '{"menu": {"slice of pizza": "2.00", "toppings": {"pepperoni": ".25","meatballs": ".35", "mushrooms": ".40","olives": ".20"},"sides": {"potato salad": "1.25","hummus": "2.50","caesar salad": "3.50","garden salad": "2.25"}, "drinks": { "soda": { "small": "1.95", "medium": "2.20","large": "2.50" }, "juice": "2.00", "water": "1.25"}}}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerText = JSON.stringify(myObj.menu.toppings.pepperoni, null, 2);
document.getElementById("demo").innerText += '\n\n' + JSON.stringify(myObj.menu.toppings, null, 2);
<p id="demo">
</p>