首页 > 解决方案 > 将 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 读取本地文件而没有真正起作用。 .

标签: javascriptjsonfile

解决方案


您可以使用 fetch api:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

旧浏览器有一个 polyfill


推荐阅读