python获取非空JSON子数组的计数

时间:2017-04-28 10:02:43

标签: python arrays json

如何计算以下json中非空dailyemails的数量?

{
   "templates":[
      {
         "id":"2c1d99d9b6b2fb417601d24c10c9b041a7d6f37b",
         "dailyemails":[
            "saaa@aa.com",
            "aaa.aaa@gmail.com"
         ],
         "name":"Registration Report"             
      },
      {
         "id":"45s4dsf4qdgze5zef1z3e2f1zevcd5s6sdfsdfsdf",
         "dailyemails":[
         ],
         "name":"Presentation"             
      },
      {
         "id":"7d7cc642ca13cc4a998cad364dfe8e623fd95ae3",
         "dailyemails":[
            "saaa@ss.com"
         ],
         "name":"Live Report"
      }

   ]
}

在Javascript中,我这样做:

var count = myArray.reduce((c, o) => c + (o.dailyemails.length? 1: 0), 0);

如何读取python中非空dailyemails的数量?

4 个答案:

答案 0 :(得分:2)

你可以做类似的事情

import json
myArray = json.loads(json_string)["templates"]
count = sum(map(lambda x: bool(x["dailyemails"]), myArray))

或者,几乎逐字翻译:

count = reduce(lambda c, o: c + (1 if o["dailyemails"] else 0), myArray, 0)

编辑:缺少结束),甚至更多的字面翻译。

答案 1 :(得分:1)

count_non_empty_dailyemails = 0
for template in json_text['templates']:
  if template['dailyemails']:
     count_non_empty_dailyemails +=1

答案 2 :(得分:1)

另一种选择:

len([item for item in js['templates'] if item['dailyemails']])

答案 3 :(得分:1)

列表理解的单行。

print len([i['dailyemails'] for i in  a["templates"] if len(i['dailyemails']) < 1])

https://repl.it/H6D6