簡體   English   中英

當我嘗試解析數據以從 JSON 獲取值時出現錯誤

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

我有以下代碼,它在瀏覽器的控制台中返回此錯誤...

(未捕獲(承諾中)SyntaxError: Unexpected token u in JSON at position 0 at Z0ECD11C1D7A287401D148A23BBD7A2F18Z.parse () at script2:2)

...在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參數為url const 這是我希望收到的 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"}]'

在此之后,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);
      }
    });
});

請注意,當我在 API 的另一頁上使用 getData function 時,它正在工作。 我只在 Chrome 上試過。 如果您需要一些額外的信息,請告訴我。 謝謝

您收到的數據已經格式化為JSON object:替換此行:

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

常量 getCityData = 數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM