我试图加载一个本地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文件中

var object1 = [

在最后

]

保存它

然后用纯js加载它

<script type="text/javascript" src="1.json"></script>

现在你可以使用它作为object1 -它已经加载!

完美的工作在Chrome和没有任何额外的库

在angular(或任何其他框架)中,你可以使用http get来加载 我是这样使用它的:

this.http.get(<path_to_your_json_file))
 .success((data) => console.log(data));

希望这能有所帮助。

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

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

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

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

你可以把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文件中声明和赋值的。

在TypeScript中,你可以使用import来加载本地JSON文件。例如,加载一个font.json:

import * as fontJson from '../../public/fonts/font_name.json';

这需要tsconfig标志——resolveJsonModule:

// tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

有关更多信息,请参阅typescript的发布说明:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html