如何在 JavaScript 中读取外部本地 JSON 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19706046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read an external local JSON file in JavaScript?
提问by user2864315
I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:
我在本地系统中保存了一个 JSON 文件并创建了一个 JavaScript 文件,以便读取 JSON 文件并打印出数据。这是 JSON 文件:
{"resource":"A","literals":["B","C","D"]}
Let's say this is the path of the JSON file: /Users/Documents/workspace/test.json.
比方说,这是JSON文件的路径:/Users/Documents/workspace/test.json。
Could anyone please help me write a simple piece of code to read the JSON file and print the data inside it in JavaScript?
谁能帮我写一段简单的代码来读取 JSON 文件并用 JavaScript 打印其中的数据?
采纳答案by Chris Pickford
You cannotmake a AJAX call to a local resource as the request is made using HTTP.
您不能对本地资源进行 AJAX 调用,因为该请求是使用 HTTP 发出的。
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
解决方法是运行本地网络服务器,提供文件并对本地主机进行 AJAX 调用。
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():
在帮助您编写代码来读取 JSON 方面,您应该阅读以下文档jQuery.getJSON():
回答by Ashfedy
For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
要使用 javascript 读取外部本地 JSON 文件 (data.json),首先创建您的 data.json 文件:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Mention the path of the json file in the script source along with the javascript file.
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script>Get the Object from the json file
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
在脚本源中提及 json 文件和 javascript 文件的路径。
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script>从json文件中获取对象
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
For more information, see this reference.
有关更多信息,请参阅此参考资料。
回答by Stano
The loading of a .jsonfilefrom harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
.json从硬盘加载文件是一个异步操作,因此需要指定一个回调函数在文件加载后执行。
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);
});
This function works also for loading a .htmlor .txtfiles, by overriding the mime type parameter to "text/html", "text/plain"etc.
此功能也用于加载.html或.txt文件,通过重写MIME类型参数"text/html","text/plain"等等。
回答by musicformellons
When in Node.js or when using require.js in the browser, you can simply do:
当在Node.js的,或在浏览器中使用require.js时,你可以简单地做:
let json = require('/Users/Documents/workspace/test.json');
Do note: the file is loaded once, subsequent calls will use the cache.
请注意:文件加载一次,后续调用将使用缓存。
回答by Syed Ayesha Bebe
- First, create a json file. In this example my file is words.json
- 首先,创建一个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"}]
- And here is my code i.e,node.js. Note the
'utf8'argument toreadFileSync: this makes it return not aBuffer(althoughJSON.parsecan handle it), but a string. I am creating a server to see the result...
- 这是我的代码,即node.js。注意
'utf8'参数readFileSync: 这使得它返回的不是一个Buffer(虽然JSON.parse可以处理它),而是一个字符串。我正在创建一个服务器来查看结果...
var fs=require('fs');
var data=fs.readFileSync('words.json', 'utf8');
var words=JSON.parse(data);
var bodyparser=require('body-parser');
console.log(words);
var express=require('express');
var app=express();
var server=app.listen(3030,listening);
function listening(){
console.log("listening..");
}
app.use(express.static('website'));
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
- When you want to read particular id details you can mention the code as..
- 当您想阅读特定的 id 详细信息时,您可以将代码提及为..
app.get('/get/:id',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.id){
res.send(words[i]);
}
}
console.log("success");
});
- When you entered in url as
localhost:3030/get/33it will give the details related to that id....and you read by name also. My json file has simillar names with this code you can get one name details....and it didn't print all the simillar names
- 当您输入 url 时,
localhost:3030/get/33它会提供与该 ID 相关的详细信息....并且您也按名称阅读。我的 json 文件与此代码具有相似的名称,您可以获得一个名称的详细信息......并且它没有打印所有相似的名称
app.get('/get/:name',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.name){
res.send(words[i]);
}
}
console.log("success");
});
- And if you want to read simillar name details, you can use this code.
- 如果您想阅读类似的名称详细信息,可以使用此代码。
app.get('/get/name/:name',function(req,res){
word = words.filter(function(val){
return val.name === req.params.name;
});
res.send(word);
console.log("success");
});
- If you want to read all the information in the file then use this code below.
- 如果您想读取文件中的所有信息,请使用下面的代码。
app.get('/all',sendAll);
function sendAll(request,response){
response.send(words);
}
回答by Alex Glinsky
回答by lauhub
Depending on your browser, you may access to your local files. But this may not work for all the users of your app.
根据您的浏览器,您可以访问本地文件。但这可能不适用于您应用的所有用户。
To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/
为此,您可以尝试以下说明:http: //www.html5rocks.com/en/tutorials/file/dndfiles/
Once your file is loaded, you can retrieve the data using:
加载文件后,您可以使用以下方法检索数据:
var jsonData = JSON.parse(theTextContentOfMyFile);
回答by Sarah Cross
As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.
正如许多人之前提到的,这在使用 AJAX 调用时不起作用。但是,有一种方法可以解决它。使用输入元素,您可以选择您的文件。
The file selected (.json) need to have this structure:
选择的文件 (.json) 需要具有以下结构:
[
{"key": "value"},
{"key2": "value2"},
...
{"keyn": "valuen"},
]
<input type="file" id="get_the_file">
Then you can read the file using JS with FileReader():
然后你可以使用 JS 和 FileReader() 读取文件:
document.getElementById("get_the_file").addEventListener("change", function() {
var file_to_read = document.getElementById("get_the_file").files[0];
var fileread = new FileReader();
fileread.onload = function(e) {
var content = e.target.result;
// console.log(content);
var intern = JSON.parse(content); // Array of Objects.
console.log(intern); // You can index every object
};
fileread.readAsText(file_to_read);
});
回答by user7394313
If you are using local files, why not just packade the data as a js object?
如果您使用的是本地文件,为什么不直接将数据打包为一个 js 对象呢?
data.js
数据.js
MyData = { resource:"A",literals:["B","C","D"]}
No XMLHttpRequests, no parsing, just use MyData.resourcedirectly
没有XMLHttpRequest的,没有解析,只需使用MyData.resource直接
回答by Antonio Carlos Del Grande Juni
Very simple.
Rename your json file to ".js" instead ".json".
很简单。
将您的 json 文件重命名为“.js”而不是“.json”。
<script type="text/javascript" src="my_json.js"></script>
So follow your code normally.
因此,请正常遵循您的代码。
<script type="text/javascript">
var obj = JSON.parse(contacts);
However, just for information, the content my json it's looks like the snip below.
但是,仅供参考,我的 json 内容看起来像下面的片段。
contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';

