Javascript解析嵌套的JSON对象

时间:2015-02-21 17:43:46

标签: javascript json parsing object nested

我是javascript的新手,我正在尝试解析和操作下面的数据但不太确定如何去做。有人可以帮忙吗?

JSON数据

{
    "2009-01": {
        "bbcfour": 324,
        "bbcnews24": 1075,
        "bbcone": 940,
        "bbcthree": 441,
        "bbctwo": 1040,
        "cbbc": 898,
        "cbeebies": 1343
    },
    "2009-02": {
        "bbcfour": 295,
        "bbcnews24": 958,
        "bbcone": 904,
        "bbcthree": 434,
        "bbctwo": 1038,
        "cbbc": 793,
        "cbeebies": 1246
    }}

的JavaScript

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-language" content="en" />
<meta http-equiv="Content-Type" content="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<link href="main.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="jquery-2.1.1.js"></script>
<script>
$.getJSON('data.json', function (data) {
    console.log(data);
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

使用for...in循环。

for..in语句以任意顺序迭代对象的可枚举属性。

   $.getJSON('data.json', function (data) {
        var resp = data;
        for(k in resp)
        {
          console.log(resp[k].bbcfour);
          console.log(resp[k].bbcnews24);
          console.log(resp[k].bbcone);
          // And so on
        }
    });