javascript - 如何将 JSON 文件中的值转换为 const?
问题描述
我目前正在做一个项目,我需要从 JSON 文件中获取数据以在 API 的获取中使用该数据(这可行),我需要从 de JSON 文件中获取的数据是latjson和lonjson以及两者将它们放入const lat: info.latjson和const 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`;
}
解决方案
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`;
}
推荐阅读
- image-processing - TensorFlow 2.2 中的自定义二值化(阈值化)图像层
- javascript - 全局变量在 setTimeout() 运行时发生变化
- javascript - Vue 2库上的Vue 2未知自定义元素
- reactjs - 使用 useState 挂钩附加数组未按预期工作
- python - 如何将 Python 代码转换为可执行文件
- javascript - 当变量具有特定值时,有没有办法 console.log ?
- wordpress - Woocommerce:$_GET 自定义参数(新订单邮件中的链接)以更新 Woocommerce 订单状态
- r - 计算分解为聚合表列的分类级别
- html - 如何重新创建 LWJGL-Website 立方体背景?
- keras - 引入类权重后,当我在 Keras 中运行神经网络时,我遇到了一个我无法弄清楚的错误