下面的代码有效。只是我不知道如何获得更深层次的“卡路里”,所以我可以将它放在 html 页面上。我可以检索 json 的第一级(如“fdcId”),但我不知道如何处理第二级和第三级,如(“卡路里”)。由于下面的代码访问了解析的 json 的第一级,似乎我只需要找到正确的语法来处理数组中不同的 json 级别。有人愿意给我举一些例子吗?非常感谢!
enter code here
<!DOCTYPE html>
<html lang="en">
<head>
<script src="p5.js"></script>
<script src="p5.sound.min.js"></script>
<script src="sketch.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>Fetch Json from API and map lat lon</title>
</head>
<body>
<h1>Where is the food?</h1>
<p>
Food ID: <span id="food"></span><br />
calories: <span id="id"></span>
</p>
<script>
const api_url = `https://api.nal.usda.gov/fdc/v1/food/1105904?api_key=############=full&nutrients=203 `;
async function getISS() {
const response = await fetch(api_url);
const data = await response.json();
const {
fdcId,
labelNutrients
} = data;
console.log(data);
document.getElementById('food').textContent = fdcId;
document.getElementById('id').textContent = labelNutrients;
}
getISS();
</script>
</body>
</html>
enter code here