首页 > 解决方案 > 如何将 JSON 文件中的值转换为 const?

问题描述

我目前正在做一个项目,我需要从 JSON 文件中获取数据以在 API 的获取中使用该数据(这可行),我需要从 de JSON 文件中获取的数据是latjsonlonjson以及两者将它们放入const lat: info.latjsonconst lon: info.latjson我试过了,我的错误是Uncaught (in promise) TypeError: Cannot read property 'lat' of undefined (在 "const: base... .")

这是我的 JSON 文件:

[
    {   
        "latjson": 21.1524,
        "lonjson": -101.7108
    },
    {
        "latjson": 21.1447,
        "lonjson":-101.6852
    }, 
    {
        "latjson": 21.1155,
        "lonjson": -101.6575
    }
]

这是我的脚本

function calcWeather(){ 
    let info  = ''

    fetch('../js/data.json') // fetch editable c:
    .then(function(response) {
        return response.json();
     })
    .then(function(myJson) {
        info = myJson
        console.log(info)
    });
     

    const lat = info.latjson;
    const long = info.lonjson;

    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
}

标签: javascriptarraysjson

解决方案


Fetch 异步运行,因此当您访问“info.latjson”时,不能保证 fetch 已经运行并将结果 JSON 分配给您的“info”对象。

要么将 fetch 下面的代码移到第二个回调中,要么使用 async await:

async function calcWeather(){ 
    const response = await fetch('../js/data.json');
    const info = await response.json();     

    const lat = info.latjson;
    const long = info.lonjson;

    const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`;
}

推荐阅读