![](/img/trans.png)
[英]How to get an object inside an array list by its property value in Python
[英]How to get an object from an json array of objects based on a value inside an object in python?
我有一个对象的json数组,看起来像这样:
{
"testcases": {
"testcase": {
"custom-fields": {
"custom-field": [{
"@id": "testCaseID",
"@content": "shotwell15"
}, {
"#text": "-",
"@id": "casecomponent"
}, {
"#text": "critical",
"@id": "caseimportance"
}]
},
"title": "Shotwell 15"
}
}
}
我正在尝试使用python并根据@id
的“值”从custom-field
数组中获取对象,如下所示:
查找对象:
{
"#text": "critical",
"@id": "caseimportance"
}
基于“案例重要性”值
我尝试使用过滤器,但这似乎不起作用。 我认为应该不难。 用javascript或ruby做的事情很简单。 在红宝石中,我可以只使用.select方法
python模块“ re”具有搜索功能,您可以查看该功能,该功能可以过滤出特定单词,然后使用索引选择该单词周围的其他单词/文本。
在Python中,您可以使用类似于Ruby的select的列表理解 :
custom_fields = data["testcases"]["testcase"]["custom-fields"]["custom-field"]
filtered = [f for f in custom_fields if f["@id"] == "caseimportance"]
Python还有一个过滤器,可以直接与Ruby的select进行比较:
Python 2:
filtered = filter(lambda f: (f["@id"] == "caseimportance"), custom_fields)
Python 3:
filtered = list(filter(lambda f: (f["@id"] == "caseimportance"), custom_fields))
列表理解通常被认为是更Pythonic的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.