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

有人有办法吗?


当前回答

如果您正在寻找一些快速和肮脏的东西,只需加载HTML文档头部的数据。

data.js

var DATA = {"a" : "b", "c" : "d"};

index . html

<html>
<head>
   <script src="data.js" ></script>
   <script src="main.js" ></script>
</head>
...
</html>

main.js

(function(){
   console.log(DATA); // {"a" : "b", "c" : "d"}
})();

我应该提到,你的堆大小(在Chrome)是大约4gb,所以如果你的数据大于,你应该找到另一种方法。如果你想检查另一个浏览器试试这个:

window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"

ES6更新:

而不是使用<script>标签来加载你的数据,你可以直接在你的main.js中使用import assert加载它

import data from './data.json' assert {type: 'json'};

其他回答

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

在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

如果你在你的本地机器上安装了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]')

美元。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

对我有效的方法如下:

输入:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Javascript代码:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>