我试图加载一个本地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的控制台中,它可以工作,我可以访问数据。

有人有办法吗?


当前回答

最近D3js能够处理本地json文件。

这就是问题所在 https://github.com/mbostock/d3/issues/673

这是D3与本地json文件一起工作的补丁。 https://github.com/mbostock/d3/pull/632

其他回答

我没有找到任何解决方案使用谷歌的闭包库。因此,为了完成列表,未来的访问者,这里是如何从本地文件加载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);
});

你可以把json放在javascript文件中。这可以使用jQuery的getScript()函数在本地加载(甚至在Chrome中)。

图- 01. - js文件:

var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'

main.js

$.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

注意,json变量是在js文件中声明和赋值的。

An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.

json_callback({"a" : "b", "c" : "d"});

接下来,在脚本中创建一个具有全局作用域的可重用变量,以保存返回的JSON。这将使返回的JSON数据可用于脚本中的所有其他函数,而不仅仅是回调函数。

var myJSON;

接下来是一个通过脚本注入检索json的简单函数。注意,我们不能在这里使用jQuery将脚本附加到文档头部,因为IE不支持jQuery .append方法。下面代码中注释掉的jQuery方法可以在其他支持.append方法的浏览器上运行。这是作为一个参考,以显示差异。

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)
}

接下来是一个简短的回调函数(与jsonp包装器同名),用于将json结果数据获取到全局变量中。

function json_callback(response){
    myJSON = response;            // Clone response JSON to myJSON object
    $('#json_script').remove();   // Remove json_script from the document
}

json数据现在可以被脚本的任何函数使用点表示法访问。举个例子:

console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console

这种方法可能与你习惯看到的有点不同,但有很多优点。首先,可以使用相同的函数在本地或从服务器加载相同的jsonp文件。作为奖励,jsonp已经是跨域友好的格式,也可以很容易地与REST类型API一起使用。

当然,没有错误处理函数,但为什么需要呢?如果您无法使用此方法获得json数据,那么您几乎可以打赌json本身存在一些问题,我会在一个好的json验证器上检查它。

我如何能够加载数据从json文件在一个JavaScript变量使用简单的JavaScript:

let mydata;
fetch('datafile.json')
    .then(response => response.json()) 
    .then(jsonResponse => mydata = jsonResponse)

在这里发帖是因为我没有找到我正在寻找的这种“解决方案”。

注意:我使用的是通过通常的“python -m http”运行的本地服务器。服务器”命令。

json_str = 字符串.raw'[{“名称”: “Jeeva”}, {“名称”: “Kumar”}]'; obj = JSON.parse(json_str); console.log(obj[0][“name”]);

我为我的cordova应用程序这样做,就像我为JSON创建了一个新的javascript文件,并将JSON数据粘贴到String中。然后使用JSON.parse解析它