使用特定键对 Python 中的对象数组进行排序

问题描述 投票:0回答:1

我的要求是遍历json中的所有对象数组,如果对象数组包含字段“StartDate”,则将该特定对象数组从具有最新StartDate的对象到具有最早StartDate的对象进行排序.

这是我的 JSON 的一个片段:

{
    "items": [
        {
            "PersonId": "0000000000000000",
            "PersonNumber": "0000000000",
            "CorrespondenceLanguage": null,
            "BloodType": null,
            "DateOfBirth": "1990-01-01",
            "DateOfDeath": null,
            "CountryOfBirth": null,
            "RegionOfBirth": null,
            "TownOfBirth": null,
            "ApplicantNumber": null,
            "CreatedBy": "CREATOR",
            "CreationDate": "2023-11-23T11:41:21.743000+00:00",
            "LastUpdatedBy": "CREATOR",
            "LastUpdateDate": "2023-12-01T21:36:38.694000+00:00",
            "workRelationships": {
                "items": [
                    {
                        "PeriodOfServiceId": "0",
                        "LegislationCode": "US",
                        "LegalEntityId": "0",
                        "LegalEmployerName": "Employer LLC",
                        "WorkerType": "E",
                        "PrimaryFlag": true,
                        "StartDate": "2013-10-21",
                        "assignments": {
                            "items": [
                                {
                                    "AssignmentId": 300000006167868,
                                    "AssignmentNumber": "A0000-0",
                                    "AssignmentName": "Project Manager",
                                    "ActionCode": "TERMINATION",
                                    "ReasonCode": "TEST",
                                    "EffectiveStartDate": "2022-12-22"
                                }
                            ]
                        }
                    },
                    {
                        "PeriodOfServiceId": "0",
                        "LegislationCode": "US",
                        "LegalEntityId": "0",
                        "LegalEmployerName": "Employer LLC",
                        "WorkerType": "E",
                        "PrimaryFlag": true,
                        "StartDate": "2023-12-08",
                        "assignments": {
                            "items": [
                                {
                                    "AssignmentId": 0,
                                    "AssignmentNumber": "A000000-0",
                                    "AssignmentName": "Project management B1",
                                    "ActionCode": "REHIRE",
                                    "ReasonCode": null,
                                    "EffectiveStartDate": "2023-12-08"
                                }
                            ]
                        }
                    }
                ]
            }
        }
    ]
}

我已经有了一个我认为应该可以解决问题的Python代码,但它似乎没有改变任何东西:

import json
from datetime import datetime

def main(input):
  adata = json.loads(input['workerData'])
  output_data = sort_arrays_with_StartDate(adata)
  return {'items': output_data}

def sort_arrays_with_StartDate(data):
    if isinstance(data, dict):
        for key, value in data.items():
            if key == 'StartDate' and isinstance(value, list):
                data[key] = sorted(value, key=lambda x: datetime.strptime(x.get('StartDate', ''), '%Y-%m-%d'), reverse=True)
            elif isinstance(value, (dict, list)):
                data[key] = sort_arrays_with_StartDate(value)  # Update the original data
    elif isinstance(data, list):
        for i, item in enumerate(data):
            data[i] = sort_arrays_with_StartDate(item)  # Update the original data
    return data  # Return the updated data

使用此代码,您会认为 WorkRelationship 中的 2 个项目将被重新排列和翻转,但通过此运行 json 似乎没有执行任何操作。

python arrays json date nested
1个回答
0
投票

StartDate
不是包含要排序的列表的键,它是列表的嵌套对象中的键。

def sort_arrays_with_StartDate(data):
    if isinstance(data, dict):
        for key, value in data.items():
            if isinstance(value, list) and len(value) > 0 and isinstance(value[0], dict) and 'StartDate' in value[0]:
                data[key] = sorted(value, key=lambda x: datetime.strptime(x.get('StartDate', ''), '%Y-%m-%d'), reverse=True)
            elif isinstance(value, (dict, list)):
                data[key] = sort_arrays_with_StartDate(value)  # Update the original data
    elif isinstance(data, list):
        for i, item in enumerate(data):
            data[i] = sort_arrays_with_StartDate(item)  # Update the original data
    return data  # Return the updated data
© www.soinside.com 2019 - 2024. All rights reserved.