我已经在我的本地系统中保存了一个JSON文件,并创建了一个JavaScript文件,以便读取JSON文件并打印数据。以下是JSON文件:

{"resource":"A","literals":["B","C","D"]}

假设这是JSON文件的路径:/Users/Documents/workspace/test.json。

谁能帮我写一段简单的代码来读取JSON文件并用JavaScript打印数据?


当前回答

使用jQuery和ajax可以很好地读取JSON文件和操作数据

    $(document).ready(function () {
        $.ajax({
            url: 'country.json',
            type: 'GET',
            dataType: 'json',
            success: function (code, statut) {
                for (let i in code) {
                    console.log(i)
                           }

            }
        });
    });

其他回答

使用Fetch API是最简单的解决方案:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

它在Firefox中工作完美,但在Chrome中你必须自定义安全设置。

将JSON文件转换为.js文件,并将JSON分配给一个变量或const,然后在你的主javascript文件中引用它。

我接受了斯塔诺精彩的回答,并把它包装成一个承诺。如果你没有像node或webpack这样的选项来从文件系统加载json文件,这可能会很有用:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");
    request.open(options.method, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {
            resolve(request.responseText);
        }
    };
    request.send(null);
});

你可以这样调用它:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'
    });

使用jQuery和ajax可以很好地读取JSON文件和操作数据

    $(document).ready(function () {
        $.ajax({
            url: 'country.json',
            type: 'GET',
            dataType: 'json',
            success: function (code, statut) {
                for (let i in code) {
                    console.log(i)
                           }

            }
        });
    });

如果你使用本地文件,为什么不把数据打包成一个js对象呢?

data.js

MyData = { resource:"A",literals:["B","C","D"]}

没有xmlhttprequest,没有解析,只使用MyData。资源直接