“Unexpected token o in JSON at position 1” 在 Node.js 中解析 JSON 数据时出现的错误

huangapple go评论68阅读模式
英文:

"Unexpected token o in JSON at position 1" Error when parsing JSON data in Node.js

问题

我正在尝试从OpenWeather API检索和输出天气数据,但我始终收到错误消息"JSON中位置1处的意外令牌o"。我正在使用request模块,并已编写以下代码:

const request = require('request');

async function getWeatherData(openweather_city_id, openweather_api_key) {
  try {
    // OpenWeather API的带有登录信息的URL
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}`;

    // 从OpenWeather API检索天气数据
    const weatherResponse = await request(apiUrl, function(error, response, body) {
      if (error) {
        console.error(error);
      } else {
        // 解析天气数据
        const weatherData = JSON.parse(body);

        // 遍历天气数据并输出位置名称和当前温度
        for (let i = 0; i < weatherData.weather.length; i++) {
          let weather = weatherData.weather[i];
          console.log(`位置是${weatherData.name},当前温度是${weatherData.main.temp}摄氏度。`);
        }
      }
    });
  } catch (error) {
    console.error(error);
  }
}

getWeatherData();

我已经尝试过在代码中删除await关键字并将request模块替换为Axios模块,但都没有解决问题。有人可以告诉我如何解决这个问题吗?

英文:

I am trying to retrieve and output weather data from the OpenWeather API, but I am consistently getting the error "Unexpected token o in JSON at position 1". I am using the request module and have written the code as follows:

const request = require(&#39;request&#39;);

async function getWeatherData(openweather_city_id, openweather_api_key) {
  try {
    // URL of the OpenWeather API with login information
    const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&amp;appid=${openweather_api_key}`;

    // Retrieve weather data from the OpenWeather API
    const weatherResponse = await request(apiUrl, function(error, response, body) {
      if (error) {
        console.error(error);
      } else {
        // Parse weather data
        const weatherData = JSON.parse(body);

        // Loop through weather data and output location name and current temperature
        for (let i = 0; i &lt; weatherData.weather.length; i++) {
          let weather = weatherData.weather[i];
          console.log(`The location is ${weatherData.name} and the current temperature is ${weatherData.main.temp} degrees Celsius.`);
        }
      }
    });
  } catch (error) {
    console.error(error);
  }
}


getWeatherData();

I've already tried running the code without the await keyword and replacing the request module with the Axios module but neither solution worked. Can anyone tell me how to fix this problem?"

答案1

得分: -1

要使用Async/await,最好使用Axios库,因为它是基于Promise的HTTP库,而且更容易阅读:

const axios = require('axios');   // 遗留的CommonJS引入方式 

async function getWeatherData(openweather_city_id, openweather_api_key) {
    try {
        const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}`;

        const weatherResponse = await axios.get(apiUrl);
        const weatherData = weatherResponse.data; // 这个库会自动将数据解析成JSON格式并存储在data属性中。
        if (!weatherData) {
            console.error(error);
        } else { 
        for (let i = 0; i < weatherData.weather.length; i++) {
            let weather = weatherData.weather[i];
            console.log(`位置是${weather.name},当前温度是${weather.main.temp}摄氏度。`);
          }
        }
    }catch (error) {
      console.error(error);
   }
}
getWeatherData(); // 带有2个参数

您可以阅读他们的文档以获取更多详细信息https://axios-http.com/docs/intro
英文:

To use Async/await it would be easier for you to use Axios library, since it's a promise-based HTTP, it's also easier to read :

const axios = require(&#39;axios&#39;);   // legacy with common.js 

async function getWeatherData(openweather_city_id, openweather_api_key) {
    try {
        const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&amp;appid=${openweather_api_key}`;
      
        const weatherResponse = await axios.get(apiUrl);
        const weatherData = weatherResponse.data; //this library will take care for you and parse in json by default in the data property.
        if (!weatherData) {
            console.error(error);
        } else { 
        for (let i = 0; i &lt; weatherData.weather.length; i++) {
            let weather = weatherData.weather[i];
            console.log(`The location is ${weather.name} and the current temperature is ${weather.main.temp} degrees Celsius.`);
          }
        }
    }catch (error) {
      console.error(error);
   }
}
getWeatherData(); // with 2 arguments

you can read their documentation for more detail : https://axios-http.com/docs/intro

huangapple
  • 本文由 发表于 2023年1月8日 08:30:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75044738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定