获取对getJSON对象值的访问权限

时间:2014-04-01 06:31:26

标签: jquery json object

我有一个帖子的JSON对象:

{

  "how-to-create-a-blog": {
    "post-url": "blog/how-to-create-a-blog.html",
    "post-image": "/posts/post-image.jpg",
    "post-title": "How to create a blog"
  },

  "how-to-create-a-mega-menu": {
    "post-url": "blog/how-to-create-a-mega-menu.html",
    "post-image": "/posts/post-image.jpg",
    "post-title": "How to create a mega menu"
  },

  "what-is-wordpress": {
    "post-url": "blog/what-is-wordpress.html",
    "post-image": "/posts/post-image.jpg",
    "post-title": "What is WordPress"
  },

  "create-your-first-wordpress-theme": {
    "post-url": "blog/create-your-first-wordpress-theme.html",
    "post-image": "/posts/post-image.jpg",
    "post-title": "Create your first wordpress theme"
  }

}

JSON对象结构是:

{

  "post-id": {
    "post-url": "",
    "post-image": "",
    "post-title": ""
  }

}

我需要使用jQuery length计算帖子数,但会出现undefined错误。

  $.getJSON('/all-posts.json', function(data) {
   var postNumbers = data[0];

    console.log(postNumbers.length);
  });

1 个答案:

答案 0 :(得分:1)

length属性可用于计算JS数组的元素数。这里有一个JS对象。所以我们必须将其转换为其键的数组并取其length

通过

Object.keys(postNumbers).length

以下是MDN doc,其中包含大量有关浏览器支持的示例和信息。

回复评论

适用于不支持Object.keys

的旧版浏览器

您可以手动定义该功能。像

if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                keys.push(k);
            }
        }
        return keys;
    };
}

如果您想计算JSON object

中唯一网址的数量
var uniqueURLS = [];
for (x in sample) {

    if(typeof(sample[x]["post-url"]) != "undefined" && sample[x]["post-url"] != null && uniqueURLS.indexOf(sample[x]["post-url"])==-1) {

        uniqueURLS.push(sample[x]["post-url"]);

    }

}

alert("there were "+uniqueURLS.length+" unique urls in there");

这是a demo fiddle