JavaScript API-为什么只显示一个JSON键/值对



我正在Github页面上测试API。我能够使用Openweather.org API。完整的JSON数据可以在浏览器中查看,但只有一个键/值对"description"会显示在我的页面上。我尝试在HTML中添加三个div标记,在weather和我想要呈现的键之间使用冒号,并且只尝试使用一个点。我在谷歌上搜索了这个问题,但没有发现任何与我的项目有关的内容。

此外,请注意,我已经注释掉了两个变量,const tconst m,因为它们会使程序失败。我试图复制const p的格式。任何指导都将不胜感激!!

这是JSON天气数据:

{
coord: {
lon: -0.13,
lat: 51.51
},
weather: [
{
id: 701,
main: "Mist",
description: "mist",
icon: "50n"
}
],
base: "stations",
main: {
temp: 278.61,
pressure: 1024,
humidity: 81,
temp_min: 276.15,
temp_max: 280.15
},
visibility: 10000,
wind: {
speed: 3.1,
deg: 100
},
clouds: {
all: 20
},
dt: 1544552400,
sys: {
type: 1,
id: 1414,
message: 0.0033,
country: "GB",
sunrise: 1544515001,
sunset: 1544543482
},
id: 2643743,
name: "London",
cod: 200
}

这是我的JavaScript:

//added strict mode to address following error message, "Uncaught SyntaxError: Unexpected token u in JSON at position 0."   'use strict';
const app = document.getElementById("root");
//add API related image
const weather = document.createElement("img");
weather.src = "weather.jpg";
const container = document.createElement("div");
container.setAttribute("class", "container");
//method to append the logo image and container div to the app root.
app.appendChild(weather);
app.appendChild(container);
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open("GET", "https://api.openweathermap.org/data/2.5/weather?q=London&APPID=14d276f4fe655e659ec92149c7cebbec", true);
request.onload = function () {    
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.weather.forEach(weather => {
const card = document.createElement("div");
card.setAttribute("class", "card");
const h1 = document.createElement("h1");
h1.textContent = weather.title;
const p = document.createElement("p");
weather.description = weather.description.substring(0, 300);
p.textContent = `${weather.description}...`;
/*const m = document.createElement("p");
weather.main = weather.main.substring(0, 300);
m.textContent = `${weather.main}...`;
const t = document.createElement("p");
weather.main.temp = weather.main.temp;
t.textContent = `${weather.main.temp}...`; */
// Append the cards to the container element
container.appendChild(card);
// Each card will contain an h1 and a p    
card.appendChild(h1);
card.appendChild(p);
});
} else {
const errorMessage = document.createElement("marquee");
errorMessage.textContent = `Hug it, it's not working!`;
app.appendChild(errorMessage);
}
}
// send request
request.send();

这是HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Testing</title>
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" 
rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script src="scripts.js"></script>
</body>
</html>

这是CSS:

* {
box-sizing: border-box
}
html {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: 'Dosis', sans-serif;
line-height: 1.6;
color: #666;
background: #F6F6F6;
}
#root {
max-width: 1200px;
margin: 0 auto;
}
h1 {
text-align: center;
padding: 1.5rem 2.5rem;
background-image: linear-gradient(120deg, #fbc2eb 0%, #a6c1ee 100%);
margin: 0 0 2rem 0;
font-size: 1.5rem;
color: white;
}
p,t {
padding: 0 2.5rem 2.5rem;
margin: 0;
}
.container {
display: flex;
flex-wrap: wrap;
}
.card {
margin: 1rem;
background: white;
box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
border-radius: 12px;
overflow: hidden;
transition: all .2s linear;
}
.card:hover {
box-shadow: 2px 8px 45px rgba(0, 0, 0, .15);
transform: translate3D(0, -2px, 0);
}
@media screen and (min-width: 600px) {
.card {
flex: 1 1 calc(50% - 2rem);
}
}
@media screen and (min-width: 900px) {
.card {
flex: 1 1 calc(33% - 2rem);
}
}
.card:nth-child(2n) h1 {
background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
}
.card:nth-child(4n) h1 {
background-image: linear-gradient(120deg, #ff9a9e 0%, #fecfef 100%);
}
.card:nth-child(5n) h1 {
background-image: linear-gradient(120deg, #ffc3a0 0%, #ffafbd 100%);
}

问题:

正如Ryan Wilson所讨论的,您看到的问题是,在遍历weather属性时,您试图访问JSON的weather属性中没有的参数。为了帮助您理解这一点,请考虑以下JSON(从您使用的API截取(:

data = {
weather: [
{
id: 721,
main: "Haze",
description: "haze",
icon: "50n"
},
{
id: 300,
main: "Drizzle",
description: "light intensity drizzle",
icon: "09n"
},
{
id: 701,
main: "Mist",
description: "mist",
icon: "50n"
}
],
base: "stations",
main: {
temp: 278.37,
pressure: 1023,
humidity: 87,
temp_min: 276.15,
temp_max: 280.15
}
id: 2643743,
name: "London",
cod: 200
};

此JSON对象有多个级别。如果我想访问薄雾天气,我必须使用data.weither[2].main,它会返回"薄雾"。这是因为我正在从天气数组的第三个项目中获取属性"main"。

现在,如果我试图通过使用data.wweather[2].main.temp来获取"temp",它不会返回任何内容,因为在第三个weather对象下没有"temp"属性。但是,在数据对象根目录的主对象下有一个temp属性。要访问它,您需要使用data.main.temp.

这如何应用于您的代码

如果你查看你的代码,你可以使用循环浏览data.weather数组

data.weather.forEach(weather => {
//...
});

对于该块的每次迭代,变量"weather"将等于data.weather数组中的一个对象。所以,如果你要使用:

data.weather.forEach(weather => {
console.log(weather.main);
});

你会得到"薄雾",然后是"细雨",然后又是"薄雾"。(基于上面显示的JSON(。

我相信你已经想清楚了,但后来你试图通过weather.main.temp来获得温度,这不是一个有效的参数。您将不得不使用data.main.temp.

我希望这能为您清除一点JSON。

真正的答案:

你的问题"为什么它只显示一个键值对?"的真正答案实际上与我上面所说的无关。如果您在发布问题时查看API发送的JSON,您会发现天气数组中只有一个对象。截至本文撰写之时,共有三个。您的代码只会创建与天气数组中的项目一样多的卡片。

请务必在此处参考Ryan Wilson的JSFiddle:https://jsfiddle.net/ep84so9m/2/他修改了你的代码,使其看起来像你想要的那样。

希望能有所帮助!

最新更新