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

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

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

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


当前回答

你可以使用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;
  };
}

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

其他回答

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

python -m SimpleHTTPServer 8181

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

您不能对本地资源进行AJAX调用,因为请求是使用HTTP发出的。

一个解决方案是运行一个本地web服务器,提供文件并对localhost进行AJAX调用。

为了帮助你编写代码来读取JSON,你应该阅读jQuery.getJSON()的文档:

http://api.jquery.com/jQuery.getJSON/

要使用javascript读取外部本地JSON文件(data. JSON),首先要创建数据。json文件:

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';

然后,

在脚本源代码中提到json文件和javascript文件的路径 <script type="text/javascript" src="data.json"></script> .json . <script type="text/javascript" src="javascript.js"></script> .js 从json文件中获取Object var mydata = JSON.parse(data); 警报(mydata [0] . name); alert (mydata [0] .age); 警报(mydata [1] . name); alert (mydata [1] .age);

有关更多信息,请参阅此参考资料。

只需使用$。getJSON和$。迭代Key /value对。 JSON文件和函数代码的内容示例:

    {
        {
            "key": "INFO",
            "value": "This is an example."
        }
    }

    var url = "file.json";         
    $.getJSON(url, function (data) {
        $.each(data, function (key, model) {
            if (model.key == "INFO") {
                console.log(model.value)
            }
        })
    });

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

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

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