我正在尝试从其他javascript文件的JSON文件中获取数据。我想通过main.js从config.json控制台记录标题。
我正在尝试了解JSON和javascript以及它们如何与该项目交互。我已经尝试使用导入和导出,它告诉我这是一个意外的标识符。我已经尝试了很多研究。
JSON代码:
{
"Info": {
"title": "Pretty Cool Title",
"bio": "Pretty cool bio too in my opinion."
}
}
JavaScript代码:
import Info from "config.json";
var info = Info
var title = info.title
console.log(title);
我的预期结果是标题(我将其设置为“非常酷的标题”)将记录在控制台中。但是,我的实际结果是“意外的标识符”
答案 0 :(得分:0)
使用fetch
。
// return json data from any file path (asynchronous)
function getJSON(path) {
return fetch(path).then(response => response.json());
}
// load json data; then proceed
getJSON('config.json').then(info => {
// get title property and log it to the console
var title = info.title;
console.log(title);
}
编辑: 这是使用 async 和 await 的方法。
async function getJSON(path, callback) {
return callback(await fetch(path).then(r => r.json()));
}
getJSON('config.json', info => console.log(info.title));