如何根据python中对象内部的值从对象的json数组中获取对象?

2024-04-24 07:06:32 发布

您现在位置: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中非常简单的事情。在ruby中,我可以使用.select方法


Tags: 对象textidjsonfieldfieldscustom数组
2条回答

在Python中,可以使用list comprehension类似于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))

然而,列表理解通常被认为是更具Python性的。你知道吗

python模块re有一个搜索函数,您可以查看它,它允许您过滤掉特定的单词,然后使用索引来选择json文件中围绕该单词的其他单词/文本。你知道吗

相关问题 更多 >