【问题标题】:How to get an object from an json array of objects based on a value inside an object in python?如何根据python中对象内部的值从对象的json数组中获取对象?
【发布时间】:2019-02-17 22:43:28
【问题描述】:

我有一个 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"
}

基于值“caseimportance”

我尝试使用过滤器,但这似乎不起作用。我觉得不应该这么难。在 javascript 或 ruby​​ 中很简单的事情。在 ruby​​ 中,我可以只使用 .select 方法

【问题讨论】:

    标签: python arrays json object find


    【解决方案1】:

    在 Python 中你可以使用 list comprehension 类似于 Ruby 的选择:

    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。

    【讨论】:

      【解决方案2】:

      python 模块 're' 有一个搜索功能,您可以查看该功能,您可以过滤掉特定的单词,然后使用索引来选择该单词周围的 json 文件的其他单词/文本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-26
        相关资源
        最近更新 更多