简体   繁体   English

当我尝试解析数据以从 JSON 获取值时出现错误

[英]Getting an error when I try to parse data to get values from JSON

I have the below code and it returns this error in console of the browser...我有以下代码,它在浏览器的控制台中返回此错误...

(Uncaught (in promise) SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at script2.js:12:32) (未捕获(承诺中)SyntaxError: Unexpected token u in JSON at position 0 at Z0ECD11C1D7A287401D148A23BBD7A2F18Z.parse () at script2:2)

...in const getCityData = JSON.parse(data.json) . ...在const getCityData = JSON.parse(data.json)中。 First, I get the value of input variable and onClick of btn is supposed to call a function to get a json data where I get "name":"Porto" , "lat":41.1494512 and "lon":-8.6107884 to pass the parameters to url const . First, I get the value of input variable and onClick of btn is supposed to call a function to get a json data where I get "name":"Porto" , "lat":41.1494512 and "lon":-8.6107884 to pass the参数为url const Here is the JSON that I expect receive:这是我希望收到的 JSON:

'[{"name":"Porto","local_names":{"ascii":"Porto","el":"Πόρτο","kn":"ಪೋರ್ಟೊ","es":"Oporto","hu":"Porto","pt":"Porto","uk":"Порту","ar":"بورتو","ru":"Порту","feature_name":"Porto","lt":"Portas","sr":"Порто"},"lat":41.1494512,"lon":-8.6107884,"country":"PT"}]'

After this, const url get the coordinates and call getData function, who returns the information that I want.在此之后,const url 获取坐标并调用 getData function,谁返回我想要的信息。

//selector variable
let input = document.querySelector('#cityinput')
let btn = document.querySelector('#add');

btn.addEventListener('click', function () {
  fetch('http://api.openweathermap.org/geo/1.0/direct?q=' + input.value + '&appid=ecef7e88947b6303121bb900373e41d2').then(res => res.json())

    .then(data => {
      const getCityData = JSON.parse(data.json)
      const [{ name }] = getCityData;
      const [{ lat }] = getCityData;
      const [{ lon }] = getCityData;
      const city = name
      const latitud = lat
      const long = lon
      const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${latitud}&lon=${long}&exclude=hourly,minutely,alerts&units=metric&appid=ecef7e88947b6303121bb900373e41d2`

      function getData(infoPerRow) {
        let fragment = new DocumentFragment();
        let names = "";
        const iconCodes = {
          '01d': '<img src="https://openweathermap.org/img/wn/01d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '01n': '<img src="https://openweathermap.org/img/wn/01n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '02d': '<img src="https://openweathermap.org/img/wn/02d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '02n': '<img src="https://openweathermap.org/img/wn/02n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '03d': '<img src="https://openweathermap.org/img/wn/03d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '03n': '<img src="https://openweathermap.org/img/wn/03n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '04d': '<img src="https://openweathermap.org/img/wn/04d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '04n': '<img src="https://openweathermap.org/img/wn/04n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '09d': '<img src="https://openweathermap.org/img/wn/09d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '09n': '<img src="https://openweathermap.org/img/wn/09n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '10d': '<img src="https://openweathermap.org/img/wn/10d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '10n': '<img src="https://openweathermap.org/img/wn/10n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '11d': '<img src="https://openweathermap.org/img/wn/11d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '11n': '<img src="https://openweathermap.org/img/wn/11n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '13d': '<img src="https://openweathermap.org/img/wn/13d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '13n': '<img src="https://openweathermap.org/img/wn/13n@2x.png" height="42" width="42" style="vertical-align: middle">',
          '50d': '<img src="https://openweathermap.org/img/wn/50d@2x.png" height="42" width="42" style="vertical-align: middle">',
          '50n': '<img src="https://openweathermap.org/img/wn/50n@2x.png" height="42" width="42" style="vertical-align: middle">',
        }

        $.getJSON(url, function (data) {

          const getData = ({ dt, temp, weather: [{ description, icon }] }) => {
            if (temp.day) temp = temp.day
            return { dt, temp, description, icon };
          }
          const { current, daily } = data;
          const result = [getData(current)]
          daily.slice(1).forEach(obj => result.push(getData(obj)));

          //Dummy Data
          info = result;
          let row;

          //infojson
          info.forEach(function (information, counter) {

            //Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length == infoPerRow) {

              //Create new row and class
              row = document.createElement("div");
              row.classList.add("row");

              //Append the row to the fragment
              fragment.appendChild(row);
            }

            //Update the content of row
            row.innerHTML += `<p>Date: ${information.dt}<br>Temperature: ${information.temp} ºC<br>Description: ${information.description}<br>${iconCodes[information.icon]}</p>`;
          });
          document.getElementById("forecast").appendChild(fragment)
        });
        getData(8);
      }
    });
});

Note that the getData function is working when I use it on the other page of API.请注意,当我在 API 的另一页上使用 getData function 时,它正在工作。 I've tried just on Chrome.我只在 Chrome 上试过。 If You need some additional information, please tell me.如果您需要一些额外的信息,请告诉我。 Thanks谢谢

The data you are receiving is already formatted as JSON object: Replace this line:您收到的数据已经格式化为JSON object:替换此行:

const getCityData = JSON.parse(data.json)常量 getCityData = JSON.parse(data.json)

With

const getCityData = data常量 getCityData = 数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM