首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JSON为什么只显示一个JavaScript密钥/值对?

JSON为什么只显示一个JavaScript密钥/值对?
EN

Stack Overflow用户
提问于 2018-12-12 03:17:09
回答 1查看 85关注 0票数 1

我正在Github页面上测试API。我能够使用Openweather.org应用程序接口。在浏览器中可以查看完整的JSON数据,但是只有一个键/值对"description“会显示在我的页面上。我尝试向HTML添加三个div标记,在天气和我想要呈现的键之间使用冒号,并且我尝试只使用一个点。我已经用谷歌搜索了这个问题,但没有找到任何与我的项目相关的东西。

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

这里是JSON的天气数据:

代码语言:javascript
复制
{
    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:

代码语言: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();

这里是

代码语言:javascript
复制
  <!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:

代码语言:javascript
复制
* {
  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%);
}
EN

回答 1

Stack Overflow用户

发布于 2018-12-12 06:48:37

The Problem:

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

代码语言:javascript
复制
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.weather2.main,它将返回" mist“。这是因为我从天气数组的第三个项目中获取了属性'main‘。

现在,如果我尝试使用data.weather2.main.temp来获取“temp”,它将不会返回任何内容,因为在第三个天气对象下没有“temp”属性。但是,在数据对象根的主对象下有一个temp属性。要访问它,您需要使用data.main.temp。

如何将其应用于您的代码?

如果您查看您的代码,您将使用以下命令遍历data.weather数组:

代码语言:javascript
复制
data.weather.forEach(weather => {
    //...
});

对于该块的每次迭代,变量‘will’将等于data.weather数组中的一个对象。因此,如果您要使用:

代码语言:javascript
复制
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/他已经修改了你的代码来做你想做的事情。

希望这能有所帮助!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53730925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档