[英]Extract list item from nested json/dictionary in python
I have a json in python that looks like the following:我在 python 中有一个 json ,如下所示:
{
"Id": "123",
"fields": {
"List1": [{
"List2": [
{
"List3": [
{ "item":"1",
"Activation": False
},
{ "item":"2",
"Activation":True
},
{ "item":"3",
"Activation":False
},
]}]}]}}
How can I write a function that return the count of Activation:False?如何编写返回 Activation:False 计数的 function? So in this example, it will return 2, since there are two items that have Activation:False.
所以在本例中,它将返回 2,因为有两个项目具有 Activation:False。
so something like:所以像:
def count_false:
#code to count false
return count
Thanks in advance!提前致谢!
This function will recursively look for the key 'Activation' and return the amount of false Activations.此 function 将递归查找密钥“激活”并返回错误激活的数量。
def count_false(your_obj):
count = 0
if isinstance(your_obj, dict):
for k, v in your_obj.items():
if k == 'Activation':
count += 1 if v is False else 0
elif isinstance(v, list):
for e in v:
count += count_false(e)
elif isinstance(v, dict):
count += count_false(v)
return count
you can also solve this with a regular expression:你也可以用正则表达式解决这个问题:
import re
import json
def count_false(your_obj):
json_string = json.dumps(your_obj)
matches = re.findall(r'"Activation": false\b', json_string)
return len(matches)
Try the below试试下面的
data = {
"Id": "123",
"fields": {
"List1": [{
"List2": [
{
"List3": [
{"item": "1",
"Activation": False
},
{"item": "2",
"Activation": True
},
{"item": "3",
"Activation": False
},
]}]}]}}
num_of_false_activation = sum(1 for x in data['fields']['List1'][0]['List2'][0]['List3'] if x['Activation'] is False)
print(num_of_false_activation)
output output
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.