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

有人有办法吗?


当前回答

美元。getJSON只适用于我在Chrome 105.0.5195.125使用等待,这是一个脚本类型的模块。

<script type="module">
    const myObject = await $.getJSON('./myObject.json');
    console.log('myObject: ' + myObject);
</script>

无须等待,我看到:

Uncaught TypeError: myObject is not iterable

当解析myObject时。

没有type="module"我看到:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

其他回答

$.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_);
                      }
                 });


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

我所做的是,首先,从network选项卡,记录服务的网络流量,从响应体,复制并保存json对象到本地文件中。然后用本地文件名调用函数,你应该能够在上面的jsonOutout中看到json对象。

最简单的方法:保存json文件为*.js,并包括到HTML模板作为脚本。

Js文件是这样的:

let fileJsonData = {
  someField: someValue,
  ...
}

包括如下内容:

...
<script src="./js/jsonData.js"></script>
...

include之后,你可以在全局范围内调用fileJsonData。

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

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

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

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