[英]Read Json file into a variable
I want to read a JSON file into a variable. 我想将JSON文件读入变量。 My JSON file would be named "questions.json" and will have this type of content:
我的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"
}
I have tried many things to work this out, such as: loadStrings and then parse the string as a JSON type (told me that loadStrings is undefined), really everything i found on the web with reading local files in javascript and nothign really worked.. 我已经尝试了许多方法来解决这个问题,例如:loadStrings,然后将字符串解析为JSON类型(告诉我loadStrings是未定义的),实际上我在网上找到的所有内容都是通过javascript读取本地文件而nothign确实起作用。 。
Similar question raised there: Loading local JSON file if you are using jquery, check the answer there, also reported here: 那里出现了类似的问题:如果您正在使用jquery,则加载本地JSON文件 ,检查那里的答案,也报告在这里:
$.getJSON("questions.json", function(json) {
console.log(json);
});
If you are just using javascript, check answer from xgqfrms using: 如果您仅使用javascript,请使用以下命令检查来自xgqfrms的答案:
new XMLHttpRequest(); 新的XMLHttpRequest();
You could use the fetch api: 您可以使用提取API:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.