计算JSON对象的长度[重复]

时间:2021-04-20 18:33:41

This question already has an answer here:

这个问题在这里已有答案:

I have JSON which looks like this:

我有JSON,看起来像这样:

{
  "item1": {
    "category": "fruit",

  },
 "item2": {
    "category": "fruit",

  }
}

How can I count the no. of items inside this?

我怎么能算不上。这里面的物品?

1 个解决方案

#1


0  

As in your JSON, number of items are the number of keys. Thus, get your JSON in an variable (say obj) and use the following:

与您的JSON一样,项目数是键的数量。因此,在变量(例如obj)中获取JSON并使用以下内容:

var  obj = JSON.parse('{"item1":{"category":"fruit",},"item2":{"category":"fruit",}}');

Object.keys(obj).length;

#1


0  

As in your JSON, number of items are the number of keys. Thus, get your JSON in an variable (say obj) and use the following:

与您的JSON一样,项目数是键的数量。因此,在变量(例如obj)中获取JSON并使用以下内容:

var  obj = JSON.parse('{"item1":{"category":"fruit",},"item2":{"category":"fruit",}}');

Object.keys(obj).length;