如何从.json文件中读取javascript?

MTP*_*MTP 31 javascript json getjson

我的脚本目前看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

其中日期"x"和事件"x"是一系列html标签.此功能在页面加载(onload)时运行.我的目标是完成同样的事情,只能从本地.json文件,而不是我上面的硬编码.我已经查看了http://api.jquery.com/jQuery.getJSON/.

本地.json文件如下所示:

{"date":"July 4th", "event":"Independence Day"}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

iro*_*hon 35

当你说.json文件时,假设你的意思是"在本地文件系统上的文件".

您需要保存格式为jsonp的json数据,并使用a file:// url来访问它.

您的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>
Run Code Online (Sandbox Code Playgroud)

并且文件c:\ data\activity.jsonp包含以下行:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
Run Code Online (Sandbox Code Playgroud)

  • var activity = JSON.parse(jsonstr) .... 之后,你就可以开始了。十分感谢你的帮助。 (2认同)

She*_* S. 7

注意:截至 2018 年 7 月 12 日,其他答案均已过时。JSONP 现在被认为是一个糟糕的想法

如果您将 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();
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

它在这里不起作用,因为该文件不在此处。转到这个 w3schools 示例:https ://www.w3schools.com/js/tryit.asp?filename = tryjson_ajax

这是 JSON.parse() 的文档:https : //developer.mozilla.org/en/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
Run Code Online (Sandbox Code Playgroud)

以下是来自https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest 的XMLHttpRequests 摘要:

使用 XMLHttpRequest (XHR) 对象与服务器交互。您可以从 URL 检索数据,而无需刷新整个页面。这使 Web 页面能够仅更新页面的一部分,而不会中断用户正在执行的操作。XMLHttpRequest 在 Ajax 编程中被大量使用。

如果您不想使用 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
    }
});
Run Code Online (Sandbox Code Playgroud)

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


小智 5

实际上,您正在寻找 AJAX CALL,其中您将用 JSON 文件的链接替换 ​​URL 参数值以获取 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
    }
});
Run Code Online (Sandbox Code Playgroud)