如何在Javascript中读取JSON文件

时间:2015-10-18 19:21:17

标签: javascript jquery json

我有一个JSON文件,其中包含以下示例内容

{
    "count": 1, 
    "timestamp": 1257033601, 
    "from": "theybf.com", 
    "to": "w.sharethis.com"
}
{
    "count": 1,
    "timestamp": 1257033601,
    "from": "",
    "to": "agohq.org"
}
{
    "count": 3, 
    "timestamp": 1257033601, 
    "from": "twistysdownload.com", 
    "to": "adserving.cpxinteractive.com"
}
{
    "count": 1, 
    "timestamp": 1257033601, 
    "from": "459.cim.meebo.com", 
    "to": "459.cim.meebo.com"
}
{
    "count": 1,
    "timestamp": 1257033601,
    "from": "boards.nbc.com",
    "to": "change.menelgame.pl"
}
{
    "count": 1,
    "timestamp": 1257033601,
    "from": "mail3-12.sinamail.sina.com.cn",
    "to": "mail3-12.sinamail.sina.com.cn"
}
{
    "count": 3,
    "timestamp": 1257033601,
    "from": "mediafire.com",
    "to": "tag.contextweb.com"
}

这些内容存储在文件' data.json'中。我想阅读此文件并在HTML页面上通过javascript显示其详细信息。

有人可以帮我理解怎么做吗?我是Javascript的新手,所以需要帮助。

2 个答案:

答案 0 :(得分:2)

您需要执行AJAX请求。以下是使用javascript:

的方法
var request = new XMLHttpRequest();

request.open('GET', 'temp.json', true);


request.onload = function(){ 
    if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
    console.log('data',data);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

文件temp.json应如下所示:

[{"count": 1, "timestamp": 1257033601, "from": "theybf.com", "to": "w.sharethis.com"},
{"count": 1, "timestamp": 1257033601, "from": "", "to": "agohq.org"},
{"count": 3, "timestamp": 1257033601, "from": "twistysdownload.com", "to": "adserving.cpxinteractive.com"},
{"count": 1, "timestamp": 1257033601, "from": "459.cim.meebo.com", "to": "459.cim.meebo.com"},
{"count": 1, "timestamp": 1257033601, "from": "boards.nbc.com", "to": "change.menelgame.pl"},
{"count": 1, "timestamp": 1257033601, "from": "mail3-12.sinamail.sina.com.cn", "to": "mail3-12.sinamail.sina.com.cn"},
{"count": 3, "timestamp": 1257033601, "from": "mediafire.com", "to": "tag.contextweb.com"}]

您可以使用http://jsonprettyprint.com/

轻松验证结构

这也可以使用jQuery来完成:

$.getJSON('temp.json', function(data) {
    console.log('data',data);
});

希望这有帮助。

答案 1 :(得分:0)

JSON是指 JavaScript Object Notation ,这是一种数据交换格式您的JSON格式不正确。一个合适的JSON对象看起来像

[{"count": 1, "timestamp": 1257033601, "from": "theybf.com", "to": "w.sharethis.com"},{"count": 1, "timestamp": 1257033601, "from": "", "to": "agohq.org"}]

您可以使用JSON从所需的网址获取$.getJSON(),例如

$.getJSON( "Yoururl", function( data ) {})

然后,您可以操作data[0].count之类的数据,并根据需要使用