如何在Javascript中读取外部本地JSON文件

我在本地系统中保存了一个JSON文件,并创build了一个Javascript文件,以便读取JSON文件并将数据打印出来。 这是JSON文件:

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

让我们说这是你到JSON文件的path:

 /Users/Documents/workspace/test.json 

任何人都可以帮我写一段简单的代码来读取JSON文件,并在Javascript中打印数据。 我对JavaScript很陌生,需要一些简单的开始。 非常感谢您的帮助。

由于请求是使用HTTP进行的,因此您无法对本地资源进行AJAX调用。

解决方法是运行本地Web服务器,提供文件并对本地主机进行AJAX调用。

在帮助您编写代码来读取JSON方面,您应该阅读jQuery.getJSON()的文档:

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

为了使用javascript读取外部本地JSON文件(data.json),首先创build你的data.json文件:

 data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]'; 
  1. 在脚本源文件中提到json文件的path以及javascript文件。

     <script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script> 
  2. 从json文件获取对象

     var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age); 

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

从硬盘加载.json文件是一个asynchronous操作,因此它需要指定一个callback函数在文件加载后执行。

 function readTextFile(file, callback) { var rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4 && rawFile.status == "200") { callback(rawFile.responseText); } } rawFile.send(null); } //usage: readTextFile("/Users/Documents/workspace/test.json", function(text){ var data = JSON.parse(text); console.log(data); }); 

这个函数也适用于加载.html.txt文件,通过将MIMEtypes参数覆盖为"text/html""text/plain"

根据您的浏览器,您可能会访问您的本地文件。 但是,这可能不适用于您的应用程序的所有用户。

为此,您可以尝试从这里的说明: http : //www.html5rocks.com/en/tutorials/file/dndfiles/

一旦你的文件被加载,你可以检索数据使用:

 var jsonData = JSON.parse(theTextContentOfMyFile); 

1.首先在这里创build一个json文件,我的文件是words.json

 [{"name":"ay","id":"533"}, {"name":"kiy","id":"33"}, {"name":"iy","id":"33"}, {"name":"iy","id":"3"}, {"name":"kiy","id":"35"}, {"name":"kiy","id":"34"}] 

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

data.js

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

没有XMLHttpRequests ,没有parsing,直接使用MyData.resource

你可以简单地做:

 let json = require('/Users/Documents/workspace/test.json'); 

请注意:文件被加载一次,随后的调用将使用caching。

既然你有一个Web应用程序,你可能有一个客户端和一个服务器。

如果你只有你的浏览器,并且你想从你的浏览器中运行的JavaScript中读取本地文件,这意味着你只有一个客户端。 出于安全原因,浏览器不应该让你做这样的事情。

但是,正如lauhub在上面解释的那样,这似乎是工作的:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

其他的解决scheme是在你的机器上的某个地方设置一个web服务器(在windows中是很小的,或者在linux中是猴子),并且用一个XMLHttpRequest或者D3库来从服务器请求文件并读取它。 服务器将从本地文件系统获取文件,并通过networking将其提供给您。

我喜欢上面的Stano / Meetar评论。 我用它来读取.json文件。 我用Promise扩展了他们的例子。 这是同样的掠夺者。 https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview

 function readTextFile(file, callback) { var rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4 && rawFile.status == "200") { callback(rawFile.responseText); } } rawFile.send(null); } //usage: // readTextFile("DATA.json", function(text){ // var data = JSON.parse(text); // console.log(data); // }); var task1 = function (){ return new Promise (function(resolve, reject){ readTextFile("DATA.json", function(text){ var data = JSON.parse(text); console.log('task1 called'); console.log(data); resolve('task1 came back'); }); }); }; var task2 = function (){ return new Promise (function(resolve, reject){ readTextFile("DATA2.json", function(text){ var data2 = JSON.parse(text); console.log('task2 called'); console.log(data2); resolve('task2 came back'); }); }); } Promise.race([task1(), task2()]) .then(function(fromResolve){ console.log(fromResolve); }); 

JSON的读取可以移动到另一个函数中,用于DRY; 但这里的例子更多的是展示如何使用promise。

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

如果您在不同的文件夹中有文件,请提及完整path而不是文件名。

如果您可以运行本地Web服务器(如Chris P上面所build议的那样),并且如果您可以使用jQuery,则可以尝试http://api.jquery.com/jQuery.getJSON/