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

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

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

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


当前回答

当在Node.js中或在浏览器中使用require.js时,你可以简单地做:

let json = require('/Users/Documents/workspace/test.json');
console.log(json, 'the json obj');

注意:文件加载一次,后续调用将使用缓存。

其他回答

一个简单的解决方法是将JSON文件放在本地运行的服务器中。为此,从终端转到您的项目文件夹,并在某些端口号上启动本地服务器,例如8181

python -m SimpleHTTPServer 8181

然后浏览到http://localhost:8181/应该会显示您的所有文件,包括JSON。如果您还没有安装python,请记住安装python。

我接受了斯塔诺精彩的回答,并把它包装成一个承诺。如果你没有像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>'
    });

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

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

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

你可以使用XMLHttpRequest()方法:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        //console.log("Json parsed data is: " + JSON.stringify(myObj));
       }
    };
xmlhttp.open("GET", "your_file_name.json", true);
xmlhttp.send();

您可以使用console.log语句(注释掉)查看myObj的响应。

如果你了解AngularJS,你可以使用$http:

MyController.$inject = ['myService'];
function MyController(myService){

var promise = myService.getJsonFileContents();

  promise.then(function (response) {
    var results = response.data;
    console.log("The JSON response is: " + JSON.stringify(results));
})
  .catch(function (error) {
    console.log("Something went wrong.");
  });
}

myService.$inject = ['$http'];
function myService($http){

var service = this;

  service.getJsonFileContents = function () {
    var response = $http({
      method: "GET",
      url: ("your_file_name.json")
    });

    return response;
  };
}

如果文件在不同的文件夹中,请提到完整的路径而不是文件名。

你可以像ES6模块一样导入它;

import data from "/Users/Documents/workspace/test.json"