我试图加载一个本地JSON文件,但它不会工作。下面是我的JavaScript代码(使用jQuery):
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
测试。json文件:
{"a" : "b", "c" : "d"}
什么也没有显示,Firebug告诉我数据是未定义的。在Firebug中我可以看到json。responseText和它是好的和有效的,但它是奇怪的,当我复制一行:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
如果您想让用户选择本地json文件(文件系统上的任何位置),那么下面的解决方案是可行的。
它使用FileReader和JSON。解析器(没有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>
这里有一个很好的FileReader介绍:http://www.html5rocks.com/en/tutorials/file/dndfiles/
我很惊讶从es6导入没有提到(使用小文件)
从“。/test.json”导入测试
Webpack 2<使用json加载器作为.json文件的默认值。
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
打字稿:
import test from 'json-loader!./test.json';
TS2307 (TS)无法找到模块“json-loader!./suburbs.json”
为了让它工作,我必须首先声明模块。我希望这能为某人节省几个小时的时间。
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
如果我试图从json-loader中忽略loader,我从webpack中得到以下错误:
突破性变化:不再允许省略'-loader'后缀
当使用加载器时。
你需要指定'json-loader'而不是'json',
看到https://webpack.js.org/guides/migrating/ automatic-loader-module-name-extension-removed
如果你在你的本地机器上安装了Python(或者你不介意安装一个),这里有一个浏览器独立的解决方案,我使用的本地JSON文件访问问题:
通过创建一个将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript文件。然后,您可以使用<script>标记加载它,并调用该函数以获得所需的数据。
下面是Python代码
import json
def json2js(jsonfilepath, functionname='getData'):
"""function converting json file to javascript file: json_data -> json_data.js
:param jsonfilepath: path to json file
:param functionname: name of javascript function which will return the data
:return None
"""
# load json data
with open(jsonfilepath,'r') as jsonfile:
data = json.load(jsonfile)
# write transformed javascript file
with open(jsonfilepath+'.js', 'w') as jsfile:
jsfile.write('function '+functionname+'(){return ')
jsfile.write(json.dumps(data))
jsfile.write(';}')
if __name__ == '__main__':
from sys import argv
l = len(argv)
if l == 2:
json2js(argv[1])
elif l == 3:
json2js(argv[1], argv[2])
else:
raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')
如果您正在寻找一些快速和肮脏的东西,只需加载HTML文档头部的数据。
data.js
var DATA = {"a" : "b", "c" : "d"};
index . 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"}
})();
我应该提到,你的堆大小(在Chrome)是大约4gb,所以如果你的数据大于,你应该找到另一种方法。如果你想检查另一个浏览器试试这个:
window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"
ES6更新:
而不是使用<script>标签来加载你的数据,你可以直接在你的main.js中使用import assert加载它
import data from './data.json' assert {type: 'json'};