我如何从我的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>
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>
首先,我建议你使用textContent
,而不是innerHTML
这样的东西。
其次,您将不得不将对象myObj.menu.toppings
转换为字符串,而不是直接将其用作对象。如何将对象转换为字符串取决于您希望如何格式化。
一些快速简单的工作(但可能不是你想要的格式)是JSON.stringify(myObj.menu.toppings)
。