Javascript 加载本地 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7346563/
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
Loading local JSON file
提问by Patrick Browne
I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:
我正在尝试加载本地 JSON 文件,但它不起作用。这是我的 JavaScript 代码(使用 jQuery:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
The test.json file:
test.json 文件:
{"a" : "b", "c" : "d"}
Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText
and it is good and valid, but it's strange when I copy the line:
什么也没有显示,Firebug 告诉我数据未定义。在 Firebug 中,我可以看到json.responseText
并且它很好且有效,但是当我复制该行时很奇怪:
var data = eval("(" +json.responseText + ")");
in Firebug's console, it works and I can access data.
在 Firebug 的控制台中,它可以工作并且我可以访问数据。
Anyone have a solution?
有人有解决方案吗?
采纳答案by seppo0010
回答by Ehvince
I had the same need (to test my angularjs app), and the only way I found is to use require.js:
我有同样的需求(测试我的 angularjs 应用程序),我发现的唯一方法是使用 require.js:
var json = require('./data.json'); //(with path)
note: the file is loaded once, further calls will use the cache.
注意:文件被加载一次,进一步的调用将使用缓存。
More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
有关使用 nodejs 读取文件的更多信息:http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js: http://requirejs.org/
require.js:http://requirejs.org/
回答by aloisdg moving to codidact.com
In a more modern way, you can now use the Fetch API:
以更现代的方式,您现在可以使用Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)
所有现代浏览器都支持 Fetch API。(Internet Explorer 没有,但 Edge 有!)
source:
来源:
回答by Trausti Kristjansson
If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.
如果您想让用户选择本地 json 文件(文件系统上的任何位置),则以下解决方案有效。
It uses uses FileReader and JSON.parser (and no jquery).
它使用 FileReader 和 JSON.parser(没有 jquery)。
<html>
<body>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h2>Json File</h2>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
}
}
</script>
</body>
</html>
Here is a good intro on FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/
这是关于 FileReader 的一个很好的介绍:http://www.html5rocks.com/en/tutorials/file/dndfiles/
回答by jwerre
If you're looking for something quick and dirty just load the data in the head of your HTML document.
如果您正在寻找快速而肮脏的东西,只需将数据加载到 HTML 文档的头部即可。
data.js
数据.js
var DATA = {"a" : "b", "c" : "d"};
index.html
索引.html
<html>
<head>
<script src="data.js" ></script>
<script src="main.js" ></script>
</head>
...
</html>
main.js
主文件
(function(){
console.log(DATA); // {"a" : "b", "c" : "d"}
})();
I should mention that your heap size (in Chrome) is about 4GBs, so if your data is larger than that you should find another method. If you want to check another browser try this:
我应该提到你的堆大小(在 Chrome 中)大约是 4GB,所以如果你的数据大于这个,你应该找到另一种方法。如果您想检查其他浏览器,请尝试以下操作:
window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"
回答by xgqfrms
ES5 version
ES5版本
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true);
// Replace 'my_data' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState === 4 && xobj.status === 200) {
// Required use of an anonymous callback
// as .open() will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}
ES6 version
ES6版本
const loadJSON = (callback) => {
let xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true);
// Replace 'my_data' with the path to your file
xobj.onreadystatechange = () => {
if (xobj.readyState === 4 && xobj.status === 200) {
// Required use of an anonymous callback
// as .open() will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
const init = () => {
loadJSON((response) => {
// Parse JSON string into object
let actual_JSON = JSON.parse(response);
});
}
回答by SpoonHonda
I can't believe how many times this question has been answered without understanding and/or addressing the problem with the Original Poster's actual code. That said, I'm a beginner myself (only 2 months of coding). My code does work perfectly, but feel free to suggest any changes to it. Here's the solution:
我无法相信在没有理解和/或使用原始海报的实际代码解决问题的情况下,这个问题已经回答了多少次。也就是说,我自己也是初学者(只有 2 个月的编码时间)。我的代码运行良好,但请随时提出任何更改建议。 这是解决方案:
//include the 'async':false parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});
//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText);
//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);
Here's a shorter way of writing the same code I provided above:
这是编写我在上面提供的相同代码的更短方法:
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
You can also use $.ajax instead of $.getJSON to write the code exactly the same way:
您还可以使用 $.ajax 而不是 $.getJSON 以完全相同的方式编写代码:
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
Finally, the last way to do thisis to wrap $.ajax in a function. I can't take credit for this one, but I did modify it a bit. I tested it and it works and produces the same results as my code above. I found this solution here --> load json into variable
最后,执行此操作的最后一种方法是将 $.ajax 包装在一个函数中。我不能相信这个,但我确实修改了一点。我测试了它,它可以工作并产生与我上面的代码相同的结果。我在这里找到了这个解决方案 --> 将json 加载到变量中
var json = function () {
var jsonTemp = null;
$.ajax({
'async': false,
'url': "http://spoonertuner.com/projects/test/test.json",
'success': function (data) {
jsonTemp = data;
}
});
return jsonTemp;
}();
document.write(json.a);
console.log(json);
The test.jsonfile you see in my code above is hosted on my server and contains the same json data object that he (the original poster) had posted.
您在上面的代码中看到的test.json文件托管在我的服务器上,并包含他(原始发布者)发布的相同 json 数据对象。
{
"a" : "b",
"c" : "d"
}
回答by Ogglas
I'm surprised import from es6 has not been mentioned (use with small files)
我很惊讶没有提到从 es6 导入(用于小文件)
Ex: import test from './test.json'
前任: import test from './test.json'
webpack 2< uses the json-loader
as default for .json
files.
webpack 2< 使用文件的json-loader
默认值.json
。
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
For TypeScript:
对于打字稿:
import test from 'json-loader!./test.json';
TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'
TS2307 (TS) 找不到模块 'json-loader!./suburbs.json'
To get it working I had to declare the module first. I hope this will save a few hours for someone.
为了让它工作,我必须先声明模块。我希望这会为某人节省几个小时。
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
If I tried to omit loader
from json-loader
I got the following error from webpack
:
如果我试图省略loader
fromjson-loader
我收到以下错误webpack
:
BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
突破性变化:在使用加载器时不再允许省略“-loader”后缀。您需要指定 'json-loader' 而不是 'json',参见https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
回答by ns-1m
Recently D3jsis able to handle local json file.
最近D3js能够处理本地 json 文件。
This is the issue https://github.com/mbostock/d3/issues/673
这是问题 https://github.com/mbostock/d3/issues/673
This is the patch inorder for D3 to work with local json files. https://github.com/mbostock/d3/pull/632
这是 D3 与本地 json 文件一起使用的补丁。 https://github.com/mbostock/d3/pull/632
回答by Samich
Try is such way (but also please note that JavaScript don't have access to the client file system):
Try 是这样的(但也请注意 JavaScript 无权访问客户端文件系统):
$.getJSON('test.json', function(data) {
console.log(data);
});