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

有人有办法吗?


当前回答

对我有效的方法如下:

输入:

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>

其他回答

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。

An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.

json_callback({"a" : "b", "c" : "d"});

接下来,在脚本中创建一个具有全局作用域的可重用变量,以保存返回的JSON。这将使返回的JSON数据可用于脚本中的所有其他函数,而不仅仅是回调函数。

var myJSON;

接下来是一个通过脚本注入检索json的简单函数。注意,我们不能在这里使用jQuery将脚本附加到文档头部,因为IE不支持jQuery .append方法。下面代码中注释掉的jQuery方法可以在其他支持.append方法的浏览器上运行。这是作为一个参考,以显示差异。

function getLocalJSON(json_url){
    var json_script  = document.createElement('script');
    json_script.type = 'text/javascript';
    json_script.src  = json_url;
    json_script.id   = 'json_script';
    document.getElementsByTagName('head')[0].appendChild(json_script);
    // $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}

接下来是一个简短的回调函数(与jsonp包装器同名),用于将json结果数据获取到全局变量中。

function json_callback(response){
    myJSON = response;            // Clone response JSON to myJSON object
    $('#json_script').remove();   // Remove json_script from the document
}

json数据现在可以被脚本的任何函数使用点表示法访问。举个例子:

console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console

这种方法可能与你习惯看到的有点不同,但有很多优点。首先,可以使用相同的函数在本地或从服务器加载相同的jsonp文件。作为奖励,jsonp已经是跨域友好的格式,也可以很容易地与REST类型API一起使用。

当然,没有错误处理函数,但为什么需要呢?如果您无法使用此方法获得json数据,那么您几乎可以打赌json本身存在一些问题,我会在一个好的json验证器上检查它。

我只是稍微编辑了一下JSON文件。

myfile。Json => myfile.js

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

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

最后,

导出默认x;

然后,

导入JsonObj from './myfile.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