python - 有没有办法检查嵌套的字典值,如果它们有 0 或 null 或空字符串,则在 python 中删除它们

标签 python json

这是我要转换成python的json文件

{
    "UniqueId": "PO3589472",
    "FareType": 2,
    "BookedBy": "Api ",
    "OrderBy": "Api ",
    "ClientBalance": 0,
    "Error": null,
    "Success": true,
    "TktTimeLimit": "2022-08-10T14:11:45",
    "Category": 21,
    "Status": 21,
    "RefundMethod": 1,
    "TravelItinerary": {
        "ItineraryInfo": {
            "ItineraryPricing": {
                "BaseFare": 8469250,
                "ServiceTax": 0,
                "TotalTax": 993000,
                "TotalFare": 9462250,
                "TotalCommission": 0,
                "Currency": "IRR"
            },
            "CustomerInfoes": [
                {
                    "Customer": {
                        "Gender": 0,
                        "PassengerType": 1,
                        "PassportNumber": "",
                        "NationalId": "1829961233",
                        "Nationality": "IR",
                        "DateOfBirth": "1996-07-08T00:00:00",
                        "PassportExpireDate": "0001-01-01T00:00:00",
                        "PassportIssueCountry": "IR",
                        "PassportIssueDate": "2022-08-10T00:00:00",
                        "PaxName": {
                            "PassengerFirstName": "MAJID",
                            "PassengerMiddleName": null,
                            "PassengerLastName": "MAJIDIFAR",
                            "PassengerTitle": 0
                        }
                    },
                    "ETickets": "8151405444745",
                    "ETicketNumbers": [
                        {
                            "ETicketNumber": "8151405444745",
                            "EticketStatus": 1,
                            "IsRefunded": false,
                            "DateOfIssue": "2022-08-10T13:58:47",
                            "AirlinePnr": "TXNXM",
                            "TotalRefund": 0
                        }
                    ]
                }
            ],
            "ReservationItems": [
                {
                    "AirEquipmentType": "737",
                    "AirlinePnr": "TXNXM",
                    "ArrivalAirportLocationCode": "ABD",
                    "ArrivalDateTime": "2022-08-17T23:25:00",
                    "ArrivalTerminal": "",
                    "Baggage": "20KG",
                    "DepartureAirportLocationCode": "THR",
                    "DepartureDateTime": "2022-08-17T22:05:00",
                    "DepartureTerminal": "Terminal 4",
                    "FlightNumber": "3750",
                    "JourneyDuration": "01:20",
                    "JourneyDurationPerMinute": 0,
                    "MarketingAirlineCode": "EP",
                    "OperatingAirlineCode": "EP",
                    "ResBookDesigCode": "Y",
                    "StopQuantity": 0,
                    "IsCharter": false,
                    "TechnicalStops": [],
                    "IsReturn": false,
                    "CabinClassCode": 1
                }
            ],
            "TripDetailPtcFareBreakdowns": [
                {
                    "PassengerTypeQuantity": {
                        "PassengerType": 1,
                        "Quantity": 1
                    },
                    "TripDetailPassengerFare": {
                        "BaseFare": 8469250,
                        "ServiceTax": 0,
                        "Tax": 993000,
                        "TotalFare": 9462250,
                        "Commission": 0,
                        "Currency": "IRR"
                    }
                }
            ],
            "PhoneNumber": "09359276735",
            "Email": "info@iran-tech.com",
            "ItineraryFareFamily": null
        },
        "BookingNotes": [],
        "Services": []
    },
    "ValidatingAirlineCode": "EP",
    "DirectionInd": 1,
    "OnlineCheckIn": false,
    "AirRemark": [],
    "curl_error": false
}

最佳答案

如前所述,这需要递归。这是一个例子:

import json
from collections.abc import Callable, Hashable
from typing import Any


def filter_dict(
    dictionary: dict[Hashable, Any],
    exclude_func: Callable[[Any], bool],
) -> None:
    discard = set()
    for key, value in dictionary.items():
        if isinstance(value, dict):
            filter_dict(value, exclude_func)
        elif exclude_func(value):
            discard.add(key)
    for key in discard:
        del dictionary[key]


def is_nothing(value: Any) -> bool:
    return value is None or value == 0 or value == ""


def main() -> None:
    j = "{}"  # Your JSON string here
    d = json.loads(j)
    filter_dict(d, is_nothing)
    print(json.dumps(d, indent=4))


if __name__ == '__main__':
    main()

它不处理嵌套在数组中的 JSON 对象(即嵌套在列表中的字典),但我认为您可以自己构建它。

关于python - 有没有办法检查嵌套的字典值,如果它们有 0 或 null 或空字符串,则在 python 中删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73949719/

相关文章:

javascript - 无需解析即可获取ajax输出

json - AWS API Gateway 正文映射模板中的原始正文有效负载

python - Google cloudml 总是给我相同的结果

python - 如何在Python中从用户输入中找到关键字?

python - PYQT 在图片上绘制选择矩形

json - 在 Python 中使用 ISODate 解析 JSON 文件

python - PyGame 窗口中未显示矩形

python - 确定numpy数组中的重复值并将它们添加到另一列python中

json - 如何使用 SwiftyJSON 从具有多个对象和数组的 JSON 中读取值

javascript - JSON 在我的 JavaScript 中被全局修改...为什么?