我试图加载一个本地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'};

其他回答

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

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

我不敢相信有多少次这个问题在没有理解和/或用原始海报的实际代码解决问题的情况下被回答了。也就是说,我自己是一个初学者(只有2个月的编码)。我的代码确实工作得很完美,但请随意提出任何更改建议。下面是解决方案:

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});  

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText); 

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

下面是我上面提供的相同代码的一种更短的方式:

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

你也可以使用$。用Ajax代替$。getJSON以完全相同的方式编写代码:

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

最后,最后一种方法是对$进行换行。函数中的Ajax。这不是我的功劳,但我确实做了一些修改。我测试了它,它工作并产生与上面的代码相同的结果。我在这里找到了这个解决方案——>加载json到变量

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}(); 

document.write(json.a);
console.log(json);

测试。你在上面的代码中看到的Json文件托管在我的服务器上,包含相同的Json数据对象,他(原始海报)已经发布。

{
    "a" : "b",
    "c" : "d"
}

我也有同样的需求(测试我的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文件在一个JavaScript变量使用简单的JavaScript:

let mydata;
fetch('datafile.json')
    .then(response => response.json()) 
    .then(jsonResponse => mydata = jsonResponse)

在这里发帖是因为我没有找到我正在寻找的这种“解决方案”。

注意:我使用的是通过通常的“python -m http”运行的本地服务器。服务器”命令。

对我有效的方法如下:

输入:

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>