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

isr3a4wc  于 2024-01-09  发布在  Python
关注(0)|答案(1)|浏览(138)

我的要求是遍历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似乎没有任何作用。

jaxagkaj

jaxagkaj1#

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

字符串

相关问题