Javascript 加载本地JSON文件
我正在尝试加载一个本地JSON文件,但它无法工作。以下是我的JavaScript代码(使用jQuery): test.json文件:Javascript 加载本地JSON文件,javascript,jquery,json,firebug,local-files,Javascript,Jquery,Json,Firebug,Local Files,我正在尝试加载一个本地JSON文件,但它无法工作。以下是我的JavaScript代码(使用jQuery): test.json文件: {"a" : "b", "c" : "d"} 没有显示任何内容,Firebug告诉我,数据未定义。在Firebug中,我可以看到json.responseText,它是好的和有效的,但是当我复制这行时,它很奇怪: var data = eval("(" +jso
{"a" : "b", "c" : "d"}
没有显示任何内容,Firebug告诉我,数据
未定义。在Firebug中,我可以看到json.responseText
,它是好的和有效的,但是当我复制这行时,它很奇怪:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据
有人有解决方案吗?是异步的,因此您应该:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
Try就是这样(但也请注意JavaScript没有访问客户端文件系统的权限):
如果您正在使用JSON的本地数组-如您在问题(test.JSON)中的示例所示,那么您可以使用JQuery的
parseJSON()
方法->
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
getJSON()
用于从远程站点获取JSON-它在本地无法工作(除非您使用的是本地HTTP服务器)最近能够处理本地JSON文件
这就是问题所在
这是D3使用本地json文件的补丁。
我也有同样的需求(测试我的angularjs应用程序),我找到的唯一方法就是使用require.js:
var json = require('./data.json'); //(with path)
注意:文件加载一次,后续调用将使用缓存
有关使用nodejs读取文件的详细信息:
require.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)
}
。。。并且是这样使用的
load_json("test2.html.js")
…这是
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
如果您想让用户选择本地json文件(文件系统中的任何位置),那么下面的解决方案可以工作 它使用FileReader和JSON.parser(没有jquery)
Json文件
函数loadFile(){
var输入,文件,fr;
if(typeof window.FileReader!=“函数”){
警报(“此浏览器尚不支持文件API。”);
返回;
}
输入=document.getElementById('fileinput');
如果(!输入){
警报(“嗯,找不到fileinput元素。”);
}
如果(!input.files){
警报(“此浏览器似乎不支持文件输入的`files`属性。”);
}
如果(!input.files[0]),则为else{
警报(“请在单击“加载”之前选择一个文件”);
}
否则{
file=input.files[0];
fr=新文件读取器();
fr.onload=接收到的文本;
fr.readAsText(文件);
}
函数receivedText(e){
让线=e.target.result;
var newArr=JSON.parse(行);
}
}
下面是关于FileReader的一个很好的介绍:$.ajax({
url:“Scripts/testingJSON.json”,
//强制将其作为文本处理
数据类型:“文本”,
成功:功能(数据测试){
//下载的数据,因此我们称之为parseJSON函数
//并传递下载的数据
var json=$.parseJSON(dataTest);
//现在json变量包含json格式的数据
//让我们展示几个项目
$.each(json,函数(i,jsonObjectList){
对于(var index=0;index
我还没有找到任何使用谷歌闭包库的解决方案。因此,为了完成未来访问者的列表,以下是如何使用闭包库从本地文件加载JSON:
goog.net.XhrIo.send('../appData.json', function(evt) {
var xhr = evt.target;
var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
console.log(obj);
});
如果您正在寻找一些快速而肮脏的东西,只需将数据加载到HTML文档的头部即可 data.js
var DATA={“a”:“b”,“c”:“d”};
index.html
...
main.js
world width: 500
(函数(){
console.log(数据);//{“a”:“b”,“c”:“d”}
})();
我应该提到,您的堆大小(在Chrome中)约为4GB,因此,如果您的数据大于4GB,您应该找到另一种方法。如果要检查其他浏览器,请尝试以下操作:
window.performance.memory.jsHeapSizeLimit/1024/1024/1024+“GBs”
//“4.046875 GBs”
在angular(或任何其他框架)中,可以使用http get加载
我是这样用的:
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
this.http.get(console.log(data));
希望这能有所帮助。如果您的本地计算机上安装了Python(或者您不介意安装Python),下面是一个与浏览器无关的解决本地JSON文件访问问题的方法,我使用: 通过创建将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript。然后,您可以使用tag加载它,并调用函数来获取所需的数据 来了 如何使用
XMLHttpRequest
加载本地json
文件
ES5版本
//需要使用匿名回调,
//as.open()将不返回值,而只是在异步模式下返回未定义的值!
函数loadJSON(回调){
var xObj=新的XMLHttpRequest();
重写emimetype(“application/json”);
open('GET','./data.json',true);
//1.将“./data.json”替换为文件的本地路径
xObj.onreadystatechange=函数(){
if(xObj.readyState==4&&xObj.status==200){
//2.调用回调函数
回调(xObj.responseText);
}
};
xObj.send(空);
}
函数init(){
loadJSON(函数(响应){
//3.将JSON字符串解析为JSON对象
log('response=',response);
var json=json.parse(响应);
log(“您的本地JSON=”,JSON.stringify(JSON,null,4));
//4.渲染到您的页面
const app=document.querySelector(“#app”);
app.innerHTML=''+JSON.stringify(JSON,null,4)+'';
//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);
});
}
init()代码>
加载。。。
我无法相信,在没有理解和/或用原始海报的实际代码解决问题的情况下,这个问题被回答了多少次。也就是说,我自己也是一个初学者(仅此而已)
goog.net.XhrIo.send('../appData.json', function(evt) {
var xhr = evt.target;
var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
console.log(obj);
});
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
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]')
//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);
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
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);
{
"a" : "b",
"c" : "d"
}
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
json_callback({"a" : "b", "c" : "d"});
var myJSON;
function getLocalJSON(json_url){
var json_script = document.createElement('script');
json_script.type = 'text/javascript';
json_script.src = json_url;
json_script.id = 'json_script';
document.getElementsByTagName('head')[0].appendChild(json_script);
// $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}
function json_callback(response){
myJSON = response; // Clone response JSON to myJSON object
$('#json_script').remove(); // Remove json_script from the document
}
console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console
var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
$.getScript('map-01.js')
.done(function (script, textStatus) {
var map = JSON.parse(json); //json is declared in the js file
console.log("world width: " + map.worldWidth);
drawMap(map);
})
.fail(function (jqxhr, settings, exception) {
console.log("error loading map: " + exception);
});
world width: 500
function readTextFile(srcfile) {
try { //this is for IE
var fso = new ActiveXObject("Scripting.FileSystemObject");;
if (fso.FileExists(srcfile)) {
var fileReader = fso.OpenTextFile(srcfile, 1);
var line = fileReader.ReadLine();
var jsonOutput = JSON.parse(line);
}
} catch (e) {
}
}
readTextFile("C:\\Users\\someuser\\json.txt");
import test from 'json-loader!./test.json';
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json
<html>
<head>
<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script>
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function gethtmlcontents(){
path = window.location.search.substr(1)
var rawFile = new XMLHttpRequest();
var my_file = rawFile.open("GET", path, true) // Synchronous File Read
//alert('Starting to read text')
rawFile.onreadystatechange = function ()
{
//alert("I am here");
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
//alert(allText)
var json_format = JSON.stringify(JSON.parse(allText), null, 8)
//output(json_format)
output(syntaxHighlight(json_format));
}
}
}
rawFile.send(null);
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
gethtmlcontents();
</script>
</head>
<body>
</body>
</html>
import * as fontJson from '../../public/fonts/font_name.json';
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
let fileJsonData = {
someField: someValue,
...
}