使用jQuery和Javascript解析本地JSON文件 [英] Parse local JSON file with jQuery and Javascript
问题描述
我正在尝试解析计算机上的JSON文件。我想解析它。 JSON文件具有以下结构:
I'm trying to parse a JSON file located on my computer. I want to parse it. The JSON file has this structure:
{
"sites": {
"site": [
{
"id": "01",
"name": "Sito 1",
"src": "localhost/root/coupon/sito1",
"expiryDate": "29 Ago 2013"
},
{
"id": "02",
"name": "Sito 2",
"src": "localhost/root/coupon/sito2",
"expiryDate": "30 Ago 2013"
},
{
"id": "Sito 3",
"name": "Sito 3",
"src": "localhost/root/coupon/sito2",
"expiryDate": "31 Ago 2013"
}
]
}
}
在我的html中我导入我创建了一个jQuery库,它将在加载页面时加载。代码如下:
In my html I import the jQuery library and I made a function that will load when the page is loaded. The code is below:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<title>Lista coupon</title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8">
function loadJson() {
window.alert("Carico il contenuto del file JSON per popolare la lista");
$(document).ready(function()
{
$.getJSON('data.json', function(json) {
console.log(json);
});
});
}
</script>
</head>
<body onload="loadJson();">
<div id="header">
<h1>Lista coupon salvati</h1>
</div>
<div id="content">
<p>Di seguito trovi tutte le promozioni salvate</p>
</div>
<div id="footer">
</div>
</body>
</html>
现在我在firebug控制台上看到它可以正确读取JSON文件,但我不知道如何解析这个JSON。我在谷歌搜索,但我发现很多使用远程JSON的例子。你能帮我理解如何解析本地JSON文件吗?
谢谢
Now I saw on firebug console that it can read correctly the JSON file, but I don't know how to parse this JSON. I searched in google, but I found a lot of example that use a remote JSON. Can you help me to understand how to parse a local JSON file? Thank you
PS:请注意我在这里发布的网站是为移动浏览器制作的。
PS: note the site I post on here it's made for mobile browser.
推荐答案
getJSON
将为您解析它。
只需删除 var obj = $ .parseJSON(json);
line(因为这将对对象进行字符串化并尝试将其解析为JSON(它不会是))。
Just remove the var obj = $.parseJSON(json);
line (since that will stringify the object and try to parse it as JSON (which it won't be)).
这篇关于使用jQuery和Javascript解析本地JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!