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

如何从JSON文件读取字段赋值给const变量,解决TypeError报错?

问题原因

  1. 异步执行顺序错误:fetch是异步网络请求,then回调仅会在请求成功返回后执行。你当前把依赖返回数据的lat/long赋值、base拼接逻辑写在了then外部,代码执行时请求还未完成,info还是初始的空字符串,读取不存在的属性自然会抛出undefined报错。
  2. 数据结构匹配错误:你的JSON文件根结构是数组,包含3组坐标对象,直接用info.latjson读取数组属性是无效操作,需要先指定数组下标选中对应坐标对象再读取属性。

修复代码

链式.then写法

function calcWeather(){ 
    fetch('../js/data.json')
    .then(function(response) {
        return response.json();
     })
    .then(function(info) {
        // 所有依赖返回数据的逻辑全部移入then回调内
        // 示例取数组第一组坐标,可根据业务需求替换下标
        const lat = info[0].latjson;
        const long = info[0].lonjson;
        const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
        // 后续调用天气API的逻辑写在这里
    });
}

async/await 更简洁写法

async function calcWeather(){ 
    const response = await fetch('../js/data.json')
    const info = await response.json()
    // 按需选择数组下标
    const lat = info[0].latjson;
    const long = info[0].lonjson;
    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
    // 后续业务逻辑
}

内容的提问来源于stack exchange,提问作者Martín JF

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:36:04