Pat*_*wne 299 javascript jquery firebug json local-files
我正在尝试加载本地JSON文件,但它无法正常工作.这是我的JavaScript代码(使用jQuery:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
Run Code Online (Sandbox Code Playgroud)
test.json文件:
{"a" : "b", "c" : "d"}
Run Code Online (Sandbox Code Playgroud)
没有显示任何内容,Firebug告诉我数据未定义.在Firebug中,我可以看到json.responseText并且它是好的和有效的,但是当我复制该行时很奇怪:
var data = eval("(" +json.responseText + ")");
Run Code Online (Sandbox Code Playgroud)
在Firebug的控制台中,它可以工作,我可以访问数据.
有人有解决方案吗?
sep*_*010 272
$.getJSON 是异步的所以你应该这样做:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
Run Code Online (Sandbox Code Playgroud)
Ehv*_*nce 154
我有同样的需求(测试我的angularjs应用程序),我找到的唯一方法是使用require.js:
var json = require('./data.json'); //(with path)
Run Code Online (Sandbox Code Playgroud)
注意:文件加载一次,进一步调用将使用缓存.
有关使用nodejs读取文件的更多信息:http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js:http: //requirejs.org/
小智 77
如果要让用户选择本地json文件(文件系统上的任何位置),则以下解决方案有效.
它使用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>
Run Code Online (Sandbox Code Playgroud)
这是FileReader的一个很好的介绍:http://www.html5rocks.com/en/tutorials/file/dndfiles/
alo*_*ica 74
以更现代的方式,您现在可以使用Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
Run Code Online (Sandbox Code Playgroud)
所有现代浏览器都支持Fetch API.(Internet Explorer没有,但Edge确实!)
资源:
jwe*_*rre 69
如果您正在寻找快速而又脏的东西,只需将数据加载到HTML文档的头部即可.
data.js
var DATA = {"a" : "b", "c" : "d"};
Run Code Online (Sandbox Code Playgroud)
的index.html
<html>
<head>
<script src="data.js" ></script>
<script src="main.js" ></script>
</head>
...
</html>
Run Code Online (Sandbox Code Playgroud)
main.js
(function(){
console.log(DATA); // {"a" : "b", "c" : "d"}
})();
Run Code Online (Sandbox Code Playgroud)
xgq*_*rms 15
ace.webgeeker.xyz
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);
});
}
Run Code Online (Sandbox Code Playgroud)
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);
});
}Run Code Online (Sandbox Code Playgroud)
Mar*_*ark 15
从头开始添加到您的 JSON 文件
var object1 = [
Run Code Online (Sandbox Code Playgroud)
最后
]
Run Code Online (Sandbox Code Playgroud)
保存
然后用纯js加载它
<script type="text/javascript" src="1.json"></script>
Run Code Online (Sandbox Code Playgroud)
现在你可以将它用作 object1 - 它已经加载了!
在 Chrome 中完美运行,无需任何额外的库
小智 10
我不敢相信在没有理解和/或解决原始海报的实际代码问题的情况下已经回答了多少次这个问题.那就是说,我自己就是初学者(只有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);
Run Code Online (Sandbox Code Playgroud)
这是编写上面提供的相同代码的更简短方法:
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
Run Code Online (Sandbox Code Playgroud)
您也可以使用$ .ajax而不是$ .getJSON以完全相同的方式编写代码:
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
Run Code Online (Sandbox Code Playgroud)
最后,最后一种方法是将$ .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);
Run Code Online (Sandbox Code Playgroud)
您在上面的代码中看到的test.json文件托管在我的服务器上,并包含他(原始海报)发布的相同json数据对象.
{
"a" : "b",
"c" : "d"
}
Run Code Online (Sandbox Code Playgroud)
Ogg*_*las 10
我很惊讶从es6导入没有被提及(使用小文件)
例如: import test from './test.json'
webpack 2 <使用文件的json-loader默认值.json.
https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore
对于TypeScript:
import test from 'json-loader!./test.json';
Run Code Online (Sandbox Code Playgroud)
TS2307(TS)找不到模块'json-loader!./ suburbs.json'
为了让它工作,我必须先声明模块.我希望这会为某人节省几个小时.
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
Run Code Online (Sandbox Code Playgroud)
如果我试图省略loader,json-loader我收到以下错误webpack:
BREAKING CHANGE:使用加载器时不再允许省略'-loader'后缀.您需要指定'json-loader'而不是'json',请参阅https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed
尝试就是这样(但请注意,JavaScript无法访问客户端文件系统):
$.getJSON('test.json', function(data) {
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
最近D3js能够处理本地json文件.
这是问题 https://github.com/mbostock/d3/issues/673
这是补丁,以便D3使用本地json文件. https://github.com/mbostock/d3/pull/632
我所做的就是稍微编辑一下 JSON 文件。
myfile.json=>myfile.js
在JSON文件中,(使其成为JS变量)
{name: "Whatever"}=>var x = {name: "Whatever"}
在最后,
export default x;
然后,
import JsonObj from './myfile.js';
尝试(不成功)加载本地 json 文件时发现此线程。这个解决方案对我有用......
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
Run Code Online (Sandbox Code Playgroud)
......并且像这样使用......
load_json("test2.html.js")
Run Code Online (Sandbox Code Playgroud)
......这是<head>......
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
Run Code Online (Sandbox Code Playgroud)
在 TypeScript 中,您可以使用 import 加载本地 JSON 文件。例如加载 font.json:
import * as fontJson from '../../public/fonts/font_name.json';
Run Code Online (Sandbox Code Playgroud)
这需要一个 tsconfig 标志 --resolveJsonModule:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅 typescript 的发行说明:https : //www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html