如何让 javascript 从 .json 文件中读取?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6711002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get javascript to read from a .json file?
提问by MTP
My script currently looks like this:
我的脚本目前看起来像这样:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
其中 date"x" 和 event"x" 是一系列 html 标签。该函数在页面加载(onload)时运行。我的目标是做完全相同的事情,只从本地 .json 文件而不是我上面的硬代码。我已经检查了http://api.jquery.com/jQuery.getJSON/。
The local .json file looks like this:
本地 .json 文件如下所示:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
有什么建议?
回答by ironchefpython
Assuming you mean "file on a local filesystem" when you say .json file.
假设您说 .json 文件时的意思是“本地文件系统上的文件”。
You'll need to save the json data formatted as jsonp, and use a file:// url
to access it.
您需要将 json 数据格式保存为 jsonp,并使用 afile:// url
来访问它。
Your HTML will look like this:
您的 HTML 将如下所示:
<script src="file://c:\data\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
文件 c:\data\activity.jsonp 包含以下行:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
回答by Javed
You can do it like...Just give the proper path of your json file...
你可以这样做......只需给出你的json文件的正确路径......
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
简单地获取数据并将其附加到一个 div ......最初在警报中打印长度。
Here is my Json file: abc.json
这是我的 Json 文件:abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
回答by Sheshank S.
NOTICE:AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
注意:截至 2018 年 7 月 12 日,其他答案均已过时。JSONP 现在被认为是一个糟糕的想法
If you have your JSON as a string, JSON.parse()
will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
如果您将 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>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
它在这里不起作用,因为该文件不在此处。转到这个 w3schools 示例:https://www.w3schools.com/js/tryit.asp?filename =tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
这是 JSON.parse() 的文档:https: //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
这是一个总结:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
JSON.parse() 方法解析 JSON 字符串,构造字符串描述的 JavaScript 值或对象。可以提供一个可选的 reviver 函数来在结果对象返回之前对其执行转换。
Here's the example used:
这是使用的示例:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
以下是来自https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest 的XMLHttpRequests 摘要:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
使用 XMLHttpRequest (XHR) 对象与服务器交互。您可以从 URL 检索数据,而无需刷新整个页面。这使 Web 页面能够仅更新页面的一部分,而不会中断用户正在执行的操作。XMLHttpRequest 在 Ajax 编程中被大量使用。
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
如果您不想使用 XMLHttpRequests,那么 JQUERY 方式(我不确定为什么它不适合您)是 http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
由于它不起作用,我会尝试使用 XMLHttpRequests
You could also try AJAX requests:
您也可以尝试 AJAX 请求:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
回答by Junaid Shahid
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
实际上,您正在寻找 AJAX CALL,您将在其中将 URL 参数值替换为 JSON 文件的链接以获取 JSON 值。
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
回答by Vishnoo Rath
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.
不是将数据存储为纯 JSON,而是将其存储为 JavaScript 对象字面量;例如
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
然后,您可以在 HTML 中执行以下操作
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');