简体   繁体   中英

python get count of non-empty JSON subarrays

How can I count the number of non-empty dailyemails in the following json?

{
   "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"
      }

   ]
}

In Javascript, I am doing it like this:

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

How can I read the number of non-empty dailyemails in python?

You can do something similar

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

Or, almost word-by-word translation:

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

Edit: missing closing ) , and even more literal translation.

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

另外一个选项:

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

a one-liner with list comprehension.

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

https://repl.it/H6D6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM