简体   繁体   English

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

[英]How to get an object from an json array of objects based on a value inside an object in python?

I have a json array of objects that looks like this: 我有一个对象的json数组,看起来像这样:

{
    "testcases": {
        "testcase": {
            "custom-fields": {
                "custom-field": [{
                    "@id": "testCaseID",
                    "@content": "shotwell15"
                }, {
                    "#text": "-",
                    "@id": "casecomponent"
                }, {
                    "#text": "critical",
                    "@id": "caseimportance"
                }]
            },
            "title": "Shotwell 15"
        }
    }
}

I am trying to use python and obtain the object from within the custom-field array based on the "value" of the @id like this: 我正在尝试使用python并根据@id的“值”从custom-field数组中获取对象,如下所示:

finding the object: 查找对象:

{
   "#text": "critical",
   "@id": "caseimportance"
}

based on the value "caseimportance" 基于“案例重要性”值

I tried to use filter, but that didn't seem to work. 我尝试使用过滤器,但这似乎不起作用。 I think it shouldn't be this hard. 我认为应该不难。 something that is so simple to do in javascript or ruby. 用javascript或ruby做的事情很简单。 In ruby I could just use the .select method 在红宝石中,我可以只使用.select方法

python模块“ re”具有搜索功能,您可以查看该功能,该功能可以过滤出特定单词,然后使用索引选择该单词周围的其他单词/文本。

In Python you can use list comprehension similar to Ruby's select: 在Python中,您可以使用类似于Ruby的select的列表理解

custom_fields = data["testcases"]["testcase"]["custom-fields"]["custom-field"]
filtered = [f for f in custom_fields if f["@id"] == "caseimportance"]

Python also has a filter that is more directly comparable to Ruby's select: Python还有一个过滤器,可以直接与Ruby的select进行比较:

Python 2: Python 2:

filtered = filter(lambda f: (f["@id"] == "caseimportance"), custom_fields)

Python 3: Python 3:

filtered = list(filter(lambda f: (f["@id"] == "caseimportance"), custom_fields))

List comprehension is often considered more Pythonic however. 列表理解通常被认为是更Pythonic的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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