当我试图解析数据以从JSON中获取值时,

6vl6ewon  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(115)

我有下面的代码,它返回此错误在浏览器的控制台.
(Uncaught(in promise)SyntaxError:Unexpected token u in JSON at position 0 at JSON.parse()at script2.js:12:32)
... inconst getCityData = JSON.parse(data.json).首先,我获取输入变量的值,btn的onClick应该调用一个函数来获取json数据,其中我获取**“name”:“Perl图”“lat”:41.1494512“lon”:-8.6107884来将参数传递给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函数,该函数返回我想要的信息。

//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/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '01n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '02d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '02n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '03d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '03n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '04d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '04n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '09d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '09n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '10d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '10n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '11d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '11n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '13d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '13n': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '50d': '<img src="https://openweathermap.org/img/wn/[email protected]" height="42" width="42" style="vertical-align: middle">',
          '50n': '<img src="https://openweathermap.org/img/wn/[email protected]" 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 iteration 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函数时,它正在工作。我只在Chrome上尝试过。如果您需要一些额外的信息,请告诉我。谢谢

xxls0lw8

xxls0lw81#

您正在接收的数据已被格式化为JSON对象:替换此行:
const getCityData = JSON.parse(data.json)

const getCityData = data

相关问题