我正在尝试加载本地JSON文件,但它无法正常工作。这是我的JavaScript代码(使用jQuery:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
test.json文件:
{"a" : "b", "c" : "d"}
没有显示任何内容,Firebug告诉我数据未定义。在Firebug中我可以看到json.responseText
并且它很好且有效,但是当我复制该行时很奇怪:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据。
有人有解决方案吗?
$.getJSON
是异步的,所以你应该这样做:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
尝试(失败)加载本地json文件时找到此线程。这个解决方案对我有用......
https://github.com/mbostock/d3/pull/632
......并且像这样使用......
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>
在TypeScript中,您可以使用import来加载本地JSON文件。例如,加载font.json:
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>
这需要一个tsconfig标志--resolveJsonModule:
import * as fontJson from '../../public/fonts/font_name.json';
有关更多信息,请参阅typescript的发行说明:// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
在angular(或任何其他框架)中,你可以使用http加载get我使用它像这样:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
希望这可以帮助。
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
如果您正在使用JSON的本地数组 - 正如您在问题(test.json)中的示例中所示,那么您可以使用JQuery的$.ajax({
url: "Scripts/testingJSON.json",
//force to handle it as text
dataType: "text",
success: function (dataTest) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(dataTest);
//now json variable contains data in json format
//let's display a few items
$.each(json, function (i, jsonObjectList) {
for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
}
});
}
});
方法 - >
parseJSON
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
用于从远程站点获取JSON - 它不能在本地工作(除非您使用本地HTTP服务器)
我还没有找到使用Google的Closure库的任何解决方案。因此,只需完成未来命令列表,下面是如何使用Closure库从本地文件加载JSON:
getJSON
我喜欢使用的方法是使用对象文字填充/包装json,然后使用.jsonp文件扩展名保存文件。此方法也会使原始json文件(test.json)保持不变,因为您将使用新的jsonp文件(test.jsonp)。包装器上的名称可以是任何名称,但它确实需要与用于处理jsonp的回调函数相同。我将使用您的test.json作为示例来显示'test.jsonp'文件的jsonp包装器添加。
goog.net.XhrIo.send('../appData.json', function(evt) {
var xhr = evt.target;
var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
console.log(obj);
});
接下来,在脚本中创建一个具有全局作用域的可重用变量,以保存返回的JSON。这将使返回的JSON数据可用于脚本中的所有其他函数,而不仅仅是回调函数。
json_callback({"a" : "b", "c" : "d"});
接下来是一个通过脚本注入检索json的简单函数。请注意,我们不能在这里使用jQuery将脚本附加到文档头,因为IE不支持jQuery .append方法。在下面的代码中注释掉的jQuery方法将适用于支持.append方法的其他浏览器。它包含在参考中以显示差异。
var myJSON;
接下来是一个简短的回调函数(与jsonp包装器同名),将json结果数据转换为全局变量。
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)
}
现在可以使用点表示法通过脚本的任何函数访问json数据。举个例子:
function json_callback(response){
myJSON = response; // Clone response JSON to myJSON object
$('#json_script').remove(); // Remove json_script from the document
}
这种方法可能与您以前看到的有点不同,但有许多优点。首先,可以在本地或从使用相同功能的服务器加载相同的jsonp文件。作为奖励,jsonp已经采用跨域友好格式,并且还可以轻松地与REST类型API一起使用。
当然,没有错误处理功能,但为什么需要一个呢?如果你无法使用这种方法获取json数据,那么你可以打赌你在json本身有一些问题,我会在一个好的JSON验证器上检查它。
你可以把你的json放在一个javascript文件中。这可以使用jQuery的console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console
函数在本地加载(甚至在Chrome中)。
map-01.js文件:
getScript()
main.js
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);
});
请注意,json变量是在js文件中声明和分配的。
world width: 500
我为我的cordova应用程序做了这个,就像我为JSON创建了一个新的javascript文件并将JSON数据粘贴到json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);
console.log(obj[0]["name"]);
然后用String.raw
解析它
我有同样的需求(测试我的angularjs应用程序),我找到的唯一方法是使用require.js:
var json = require('./data.json'); //(with path)
注意:文件加载一次,进一步调用将使用缓存。
有关使用nodejs读取文件的更多信息:http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs
require.js:http://requirejs.org/
JSON.parse
我所做的是,首先,从网络选项卡,记录服务的网络流量,从响应正文,复制并保存本地文件中的json对象。然后使用本地文件名调用该函数,您应该能够在上面的jsonOutout中看到json对象。
对我有用的是:
输入:
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");
Javascript代码:
http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json
我所做的是稍微编辑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>
=> myfile.json
在JSON文件中,(使其成为JS变量)
myfile.js
=> {name: "Whatever"}
在末尾,
var x = {name: "Whatever"}
然后,
export default x;
如果你在本地机器上安装了Python(或者你不介意安装一个),这里是一个独立于浏览器的解决方法,用于我使用的本地JSON文件访问问题:
通过创建一个将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript。然后,您可以使用<script>标记加载它并调用该函数以获取所需的数据。
来自import JsonObj from './myfile.js';
the Python code
如果要让用户选择本地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>
这是FileReader的一个很好的介绍:http://www.html5rocks.com/en/tutorials/file/dndfiles/
如果您正在寻找快速而又脏的东西,只需将数据加载到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"}
})()
以更现代的方式,您现在可以使用Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
所有现代浏览器都支持Fetch API。 (Internet Explorer没有,但Edge确实!)
资源:
ace.Web geek而.下一站
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);
});
}
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);
});
}
我不敢相信在没有理解和/或解决原始海报的实际代码问题的情况下已经回答了多少次这个问题。那就是说,我自己就是初学者(只有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);
这是编写上面提供的相同代码的更短方式:
var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
您也可以使用$ .ajax而不是$ .getJSON以完全相同的方式编写代码:
var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);
最后,最后一种方法是将$ .ajax包装在一个函数中。我不能相信这一点,但我确实修改了一下。我测试了它,它的工作原理与我上面的代码产生的结果相同。我在这里找到了这个解决方案 - > load json into variable
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);
您在上面的代码中看到的test.json文件托管在我的服务器上,并包含他(原始海报)发布的相同json数据对象。
{
"a" : "b",
"c" : "d"
}
我很惊讶从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';
TS2307(TS)找不到模块'json-loader!./ suburbs.json'
为了让它工作,我必须先声明模块。我希望这会为某人节省几个小时。
declare module "json-loader!*" {
let json: any;
export default json;
}
...
import test from 'json-loader!./test.json';
如果我试图从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);
});