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

myfile。Json => myfile.js

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

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

最后,

导出默认x;

然后,

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

其他回答

美元。getJSON是异步的,所以你应该这样做:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

如果您正在使用JSON的本地数组-正如您在问题(test.json)中的示例中所示,那么您可以使用JQuery的parseJSON()方法->

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

getJSON()用于从远程站点获取JSON -它不会在本地工作(除非您使用本地HTTP服务器)

在一个更现代的方式,你现在可以使用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

如果你在你的本地机器上安装了Python(或者你不介意安装一个),这里有一个浏览器独立的解决方案,我使用的本地JSON文件访问问题:

通过创建一个将数据作为JavaScript对象返回的函数,将JSON文件转换为JavaScript文件。然后,您可以使用<script>标记加载它,并调用该函数以获得所需的数据。

下面是Python代码

import json


def json2js(jsonfilepath, functionname='getData'):
    """function converting json file to javascript file: json_data -> json_data.js
    :param jsonfilepath: path to json file
    :param functionname: name of javascript function which will return the data
    :return None
    """
    # load json data
    with open(jsonfilepath,'r') as jsonfile:
        data = json.load(jsonfile)
    # write transformed javascript file
    with open(jsonfilepath+'.js', 'w') as jsfile:
        jsfile.write('function '+functionname+'(){return ')
        jsfile.write(json.dumps(data))
        jsfile.write(';}')

if __name__ == '__main__':
    from sys import argv
    l = len(argv)
    if l == 2:
        json2js(argv[1])
    elif l == 3:
        json2js(argv[1], argv[2])
    else:
        raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')

在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