将外部的"data.json"文件导入到Javascript变量中

3
这可能是重复的问题,但我找不到一个先前提出的问题来回答我的问题。
我想像这样将一个.json文件导入到我的javascript中:
var array = "data.json";

或者

var array = $.getJson('data.json');

我知道这两种方法都是错误的,请问有谁能指点一下正确的方向?非常欢迎文档

$.getJSON 有什么问题? - Andrew Li
你是指在服务器上使用JSON吗? - 16kb
它区分大小写吗?我正在使用 "$.getJson"。 - Austin Leath
@AustinLeath 是的,它是区分大小写的。 - Andrew Li
让数组等于需要('./data.json') - Lawrence Cherone
2个回答

6
这是将JSON文件导入JavaScript的方法。 导入JSON文件后,您可以使用存储JSON值的“arr”变量。
var arr = null;
$.ajax({
    'async': false,
    'global': false,
    'url': "/data.json",
    'dataType': "json",
    'success': function (data) {
        arr = data;
    }
});

如果这段代码有效,您可以考虑接受此答案。这将对寻找答案的其他人有所帮助。 - david

1
如果您的JSON是一个字符串,JSON.parse() 将会很好地工作。由于您正在从文件中加载json,因此您需要对其进行XMLHttpRequest。例如(这是w3schools.com的示例):

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>

<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>

<p id="demo"></p>


<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>

</body>
</html>

这里不起作用,因为该文件并不在此处。 不过可以参考w3schools的示例:https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

以下是 JSON.parse() 的文件说明:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

以下是一份摘要:

JSON.parse() 方法解析 JSON 字符串,构造由该字符串描述的 JavaScript 值或对象。可提供一个可选的 reviver 函数,用以在返回之前对所得到的对象执行变换(操作)。

以下是使用的示例:

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

如果您不想使用XMLHttpRequests,那么一种JQUERY方式(我不确定为什么它对您不起作用)是http://api.jquery.com/jQuery.getJSON/ 因为它没有起作用,我会尝试使用XMLHttpRequests
编辑:
您也可以尝试使用AJAX请求:
$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

文档:http://api.jquery.com/jquery.ajax/


谢谢,我会尝试这个方法。我有一个包含50,000行的文件,所以我将它存储在我的Web服务器上,并在我的应用程序中从本地机器上读取它。 - Austin Leath
如果我的回答对您有帮助,请将其标记为正确答案,因为我花了很长时间来编写它(它非常长:)) - Sheshank S.
@AustinLeath 还要记得这个答案指出了文档。 - Sheshank S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接