javascript - 将 Json 文件读入变量
问题描述
我想将一个 JSON 文件读入一个变量。我的 JSON 文件将被命名为“questions.json”,并将包含以下类型的内容:
{
question: "Question 1?",
answers: {
a: "A",
b: "B",
c: "The Correct One"
},
correctAnswer: "c"
},
{
question: "Question 2?",
answers: {
a: "A",
b: "B",
c: "The Correct One"
},
correctAnswer: "c"
}
我已经尝试了很多方法来解决这个问题,例如:loadStrings,然后将字符串解析为 JSON 类型(告诉我 loadStrings 未定义),实际上我在网上找到的所有内容都是用 javascript 读取本地文件而没有真正起作用。 .
解决方案
您可以使用 fetch api:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
推荐阅读
- bash - bash:全局否定和多种模式的问题
- r - geom_col 值乱序
- apache - 为生产构建 Cordova 浏览器
- powershell - 收到错误“方法调用失败,因为 [System.Net.IPAddress[]] 不包含名为“Where”的方法”
- jdbc - 使用 Kafka KSQL AVRO 表作为 Kafka Connect JDBC Sink 源的问题
- hex - 如何通过网络发送“\xf4\x00\x00\x00”?
- selenium - 在 Page Object Model 中,为什么我们使用 Webelements 而不是 Strings 作为类变量呢?
- c# - 使用 AJAX,我们可以 POST 到 ViewComponent 中的方法吗?
- excel - 将表格中的值与下拉范围匹配
- c++ - 新的 Qt 应用程序未运行:突然出现大量错误