You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法从localStorage中取出已解析的JSON对象?

从localStorage的JSON对象中提取天气数据的解决方案

嗨,我看你已经搞定了API请求和localStorage存储这部分,现在要从存的JSON里提取信息对吧?先把你给出的代码片段修正补全(之前的语法里&&被转成了&&,我帮你改回来),然后一步步说怎么提取数据:

你的现有代码(修正后)

function showWeather(latitude, longitude, city) { 
  var xhttp = new XMLHttpRequest(); 
  xhttp.onreadystatechange = function() { 
    // 这里要注意状态码是status,逻辑与是&&
    if (this.readyState == 4 && this.status == 200) {
      // 把API返回的JSON字符串转成对象,再存到localStorage里
      const weatherData = JSON.parse(this.responseText);
      localStorage.setItem('weatherInfo', JSON.stringify(weatherData));
      // 调用提取数据的函数
      extractWeatherData();
    } 
  }; 
  // 替换成你实际使用的天气API地址
  xhttp.open("GET", `https://your-weather-api-url.com?lat=${latitude}&lon=${longitude}&q=${city}`, true); 
  xhttp.send(); 
}

提取localStorage中JSON数据的步骤

1. 取出并解析JSON字符串

localStorage里存的是字符串格式的JSON,所以第一步要把它取出来,用JSON.parse()转成JavaScript对象,这样才能直接访问属性。

2. 根据API结构提取信息

不同的天气API返回的JSON结构不一样,我拿常见的天气API结构举例子,你可以对照自己的API返回调整:

假设你的localStorage里存的JSON是这样的:

{
  "name": "上海",
  "main": {
    "temp": 298.15,
    "humidity": 70
  },
  "weather": [
    {
      "description": "晴转多云"
    }
  ]
}

那提取数据的函数可以这么写:

function extractWeatherData() {
  // 先从localStorage取出数据
  const storedWeatherStr = localStorage.getItem('weatherInfo');
  
  // 先判断有没有数据,避免空值报错
  if (!storedWeatherStr) {
    console.log("本地没有存储的天气数据哦");
    return;
  }

  // 转成JavaScript对象
  const weatherData = JSON.parse(storedWeatherStr);

  // 按结构提取需要的字段
  const cityName = weatherData.name;
  // 有的API返回开尔文温度,转成摄氏度保留1位小数
  const temp = (weatherData.main.temp - 273.15).toFixed(1);
  const humidity = weatherData.main.humidity;
  // weather是数组,取第一个元素的天气描述
  const weatherDesc = weatherData.weather[0].description;

  // 把提取到的数据展示到页面上
  document.getElementById('city').textContent = `城市:${cityName}`;
  document.getElementById('temp').textContent = `温度:${temp}℃`;
  document.getElementById('humidity').textContent = `湿度:${humidity}%`;
  document.getElementById('weather-desc').textContent = `天气:${weatherDesc}`;
}

几个要注意的小细节

  • 一定要先判断localStorage.getItem的返回值是不是null,不然空字符串用JSON.parse会报错
  • 仔细对照你的API返回的JSON结构,属性路径不能错,比如如果你的温度在data.main.temp下,就改成weatherData.data.main.temp
  • 如果遇到数组类型的字段(比如weather),要记得用索引取值,比如[0]取第一个元素

内容的提问来源于stack exchange,提问作者Plox333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:43:42