[Python] How to get field value from array of objects in python?

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a json file with a list of objects from which I need to get some objects with filtration.

    My json:

    [
    {
    "_id": "1",
    "type": "answer",
    "segments": [
    {
    "slug": "employees",
    "title": "employees",
    "id": "111111"
    },
    {
    "slug": "middle-employees",
    "title": "М",
    "id": "22222222"
    }
    ],
    "rubric": {
    "slug": "online",
    "title": "deal",
    "id": "123"
    }
    },
    {
    "_id": "2",
    "type": "instruction",
    "segments": [
    {
    "slug": "employees",
    "title": "employees",
    "id": "111111"
    },
    {
    "slug": "middle-employees",
    "title": "М",
    "id": "22222222"
    }
    ],
    "rubric": {
    "slug": "offline",
    "title": "off",
    "id": "345"
    }
    }
    ]


    My task is to check if there is some id value among segments array and if rubric id is some other special value. But something is wrong in my filtration and I always get empty filtered_data and I can't understand why.

    It's my first attempt to write python code, please don't be so strict.

    my python simplest code:

    def get_data_from_json(self, json_data):
    data = json.loads(json_data)
    filtered_data = [
    item for item in data
    if hasattr(item, "segments") and len(item["segments"]) != 0
    and any(seg_id in item["segments"]["id"] for seg_id in filter_config["segment_ids"])
    and item["rubric"]["id"] in filter_config["rubric_ids"]
    and item.get("type") == "answer"
    ]
    # then I'm gonna use filtered_data

    Continue reading...

Compartilhe esta Página