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

有人有办法吗?


当前回答

在尝试(不成功)加载本地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)
}

... And的用法是这样的…

load_json("test2.html.js")

...这是<head>…

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

其他回答

在尝试(不成功)加载本地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)
}

... And的用法是这样的…

load_json("test2.html.js")

...这是<head>…

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

在一个更现代的方式,你现在可以使用Fetch API:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

所有现代浏览器都支持Fetch API。(Internet Explorer没有,但Edge有!)

或者使用async/await

async function printJSON() {
    const response = await fetch("test.json");
    const json = await response.json();
    console.log(json);
}

来源:

使用取回 正在执行的取回 我能用…吗? 如何使用Fetch与async/await

我也有同样的需求(测试我的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文件。

myfile。Json => myfile.js

在JSON文件中,(将其设置为JS变量)

{name: "Whatever"} => var x = {name: "Whatever"}

最后,

导出默认x;

然后,

导入JsonObj from './myfile.js';

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

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

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