简体   繁体   English

如何遍历多级JSON

[英]How to loop through multi-level JSON

I would like to loop through each dictionary for Containers below and pull info out for each one as it relates to the top-level dictionary, my code below only loops through the last dictionary. 我想遍历下面每个容器的字典,并为每个字典提取信息,因为它与顶级字典有关,下面的代码仅循环遍历最后一个字典。 How can I fix this to loop through all dictionaries? 如何解决此问题以遍历所有词典?

JSON: JSON:

{
    "MetaData": {},
    "SRData": {
         "AddressVerified": "Y",
                    "SRNumber": "1-19066631",
                    "CreatedDate": "06/17/2015 07:22:16",
                    "UpdatedDate": "06/19/2015 04:56:39",
                    "IntegrationId": "06172015072216272",
                    "Status": "Open",
                    "CreatedByUserLogin": "MYLA-SAN2",
                    "UpdatedByUserLogin": "MYLA-SAN2",
                    "Anonymous": "N",
                    "Zipcode": "90011",
                    "Latitude": "34.0258281427",
                    "Longitude": "-118.261080295",
                    "CustomerAccessNumber": "",
                    "LADWPAccountNo": "",
                    "NewContactFirstName": "fg",
                    "NewContactLastName": "ln",
                    "NewContactPhone": "455-455-4554",
                    "NewContactEmail": "",
                    "ParentSRNumber": "1-19048641",
                    "Priority": "Normal",
                    "Language": "English",
                    "ReasonCode": "",
                    "ServiceDate": "06/18/2015 00:00:00",
                    "Source": "Call",
                    "ClosedDate": "",
                    "Email": "",
                    "FirstName": "",
                    "HomePhone": "",
                    "LastName": "",
                    "LoginUser": "",
                    "ResolutionCode": "",
                    "SRUnitNumber": "",
                    "MobilOS": "",
                    "SRAddress": "601 E 22ND ST, 90011",
                    "SRAddressName": "",
                    "SRAreaPlanningCommission": "South Los Angeles APC",
                    "SRCommunityPoliceStation": "CENTRAL BUREAU",
                    "SRCouncilDistrictMember": "Curren D. Price Jr.",
                    "SRCouncilDistrictNo": "9",
                    "SRDirection": "E",
                    "SRNeighborhoodCouncilId": "78",
                    "SRNeighborhoodCouncilName": "SOUTH CENTRAL NC",
                    "SRStreetName": "22ND",
                    "SRSuffix": "ST",
                    "SRTBColumn": "E",
                    "SRTBMapGridPage": "634",
                    "SRTBRow": "7",
                    "SRXCoordinate": "6482570",
                    "SRYCoordinate": "1831887",
                    "AssignTo": "WH",
                    "Assignee": "",
                    "Owner": "BOS",
                    "ParentSRStatus": "Open",
                    "ParentSRType": "Service Not Complete",
                    "ParentSRLinkDate": "06/19/2015 04:56:39",
                    "ParentSRLinkUser": "MYLA-SAN2",
                    "SRAreaPlanningCommissionId": "9",
                    "SRCommunityPoliceStationAPREC": "NEWTON",
                    "SRCommunityPoliceStationPREC": "13",
                    "SRCrossStreet": "",
                    "ActionTaken": "SR Created",
                    "SRCity": "",
                    "RescheduleCounter": "",
                    "SRHouseNumber": "601",
                    "ContactSuppressEmailFlag": "Y",
                    "SourceofRequestCouncil": "",
                    "CCBPremiseType": "Multi Residential",
                    "ContainerBlackCount": "",
                    "ContainerBrownCount": "",
                    "SRIntersectionDirection": "",
                    "SRApproximateAddress": "N",
                    "ContainerGreenCount": "",
                    "OtherBureauName": "",
                    "AssigneeName": "",
                    "AssigneeOrganization": "",
                    "AnotherBureauEmailId": "",
                    "CCBPremiseId": "",
        "ListOfLa311BulkyItem": {},
        "ListOfLa311DeadAnimalRemoval": {},
        "ListOfLa311BrushItemsPickup": {},
        "ListOfLa311Containers": {
            "La311Containers": [
                {
                    "ContainerNumber": "",
                    "ContainerType": "Blue Recycling",
                    "DamageonLid": "",
                    "DamageonAxle": "",
                    "DamageonBody": "",
                    "DamageonWheels": "",
                    "DeliveryReason": "Private to City Service",
                    "DriverFirstName": "",
                    "DriverLastName": "",
                    "ExchangeDetails": "",
                    "GatedCommunityMultifamilyDwelling": "",
                    "MobileHomeSpace": "",
                    "PickupReason": "",
                    "RequestFor": "Delivery",
                    "ServiceDateRendered": "",
                    "TruckNo": "",
                    "Type": "Containers",
                    "CollectionLocation": "Curb",
                    "ContainerSize": "30 Gallon (Small) Blue",
                    "LastUpdatedBy": "",
                    "ActiveStatus": "Y",
                    "NameField1": "",
                    "NameField2": "",
                    "NameField3": "",
                    "NameField4": "",
                    "NumericValueField1": "",
                    "NumericValueField2": "",
                    "NumericValueField3": "",
                    "NumericValueField4": "",
                    "PurposeofSR": "",
                    "Name": "061720150722162721"
                },
                {
                    "ContainerNumber": "2222222222222",
                    "ContainerType": "Black Refuse",
                    "DamageonLid": "",
                    "DamageonAxle": "",
                    "DamageonBody": "",
                    "DamageonWheels": "",
                    "DeliveryReason": "",
                    "DriverFirstName": "",
                    "DriverLastName": "",
                    "ExchangeDetails": "",
                    "GatedCommunityMultifamilyDwelling": "",
                    "MobileHomeSpace": "",
                    "PickupReason": "Abandoned",
                    "RequestFor": "Pickup",
                    "ServiceDateRendered": "",
                    "TruckNo": "",
                    "Type": "Containers",
                    "CollectionLocation": "Curb",
                    "ContainerSize": "90 Gallon (Large) Black",
                    "LastUpdatedBy": "",
                    "ActiveStatus": "Y",
                    "NameField1": "",
                    "NameField2": "",
                    "NameField3": "",
                    "NameField4": "",
                    "NumericValueField1": "",
                    "NumericValueField2": "",
                    "NumericValueField3": "",
                    "NumericValueField4": "",
                    "PurposeofSR": "",
                    "Name": "061720150722162722"
                },
                {
                    "ContainerNumber": "",
                    "ContainerType": "Black Refuse",
                    "DamageonLid": "",
                    "DamageonAxle": "",
                    "DamageonBody": "",
                    "DamageonWheels": "",
                    "DeliveryReason": "Exchange",
                    "DriverFirstName": "",
                    "DriverLastName": "",
                    "ExchangeDetails": "",
                    "GatedCommunityMultifamilyDwelling": "",
                    "MobileHomeSpace": "",
                    "PickupReason": "",
                    "RequestFor": "Delivery",
                    "ServiceDateRendered": "",
                    "TruckNo": "",
                    "Type": "Containers",
                    "CollectionLocation": "Curb",
                    "ContainerSize": "60 Gallon (Regular) Black",
                    "LastUpdatedBy": "",
                    "ActiveStatus": "Y",
                    "NameField1": "",
                    "NameField2": "",
                    "NameField3": "",
                    "NameField4": "",
                    "NumericValueField1": "",
                    "NumericValueField2": "",
                    "NumericValueField3": "",
                    "NumericValueField4": "",
                    "PurposeofSR": "",
                    "Name": "061720150722162743"
                },
                {
                    "ContainerNumber": "2222222222222",
                    "ContainerType": "Black Refuse",
                    "DamageonLid": "N",
                    "DamageonAxle": "Y",
                    "DamageonBody": "Y",
                    "DamageonWheels": "N",
                    "DeliveryReason": "",
                    "DriverFirstName": "",
                    "DriverLastName": "",
                    "ExchangeDetails": "",
                    "GatedCommunityMultifamilyDwelling": "",
                    "MobileHomeSpace": "",
                    "PickupReason": "",
                    "RequestFor": "Damage",
                    "ServiceDateRendered": "",
                    "TruckNo": "",
                    "Type": "Containers",
                    "CollectionLocation": "Curb",
                    "ContainerSize": "30 Gallon (Small) Black",
                    "LastUpdatedBy": "",
                    "ActiveStatus": "Y",
                    "NameField1": "",
                    "NameField2": "",
                    "NameField3": "",
                    "NameField4": "",
                    "NumericValueField1": "",
                    "NumericValueField2": "",
                    "NumericValueField3": "",
                    "NumericValueField4": "",
                    "PurposeofSR": "",
                    "Name": "061720150722162744"
                }
            ]
        }
    }
}

Code: 码:

import json


CS = 'C:\Users\GIS\Desktop\containers.json'
with open(CS) as data_file:
    CSdata = json.load(data_file)

items = []
for CSData in CSdata:
    K_Containers = CSdata['SRData']['ListOfLa311Containers']
    K_Address = CSdata['SRData']['SRAddress']
    K_FirstName = "John"
    K_Longitude = CSdata ['SRData']['Longitude']
    K_Latitude = CSdata['SRData']['Latitude']
    K_Reason =CSdata['SRData']['ReasonCode']
    K_ResolutionCode = '0'


    k_uid = ' '
    k_container_type= ' '
    k_container_number = ' '
    k_delivery_reason = ' '
    k_damage_body = ' '
    k_damage_lid = ' '
    k_container_size = ' '
    k_axle_dam = ' '
    k_wheel_dam = ' '

    try:
        for CSData in K_Containers:
            for containers in K_Containers['La311Containers']:
                containersize = containers['ContainerSize']
                if k_container_size != containersize:
                        k_container_size = containersize
    except:
        print  "Pass"



    try:
        for sr in K_Containers:
            container_type = containers ['ContainerType']
            if k_container_type != container_type:
                k_container_type = container_type

        for sr in K_Containers:
            container_number = containers ['ContainerNumber']
            if k_container_number != container_number:
                k_container_number = container_number

        for sr in K_Containers:
            deliverreason = containers ['DeliveryReason']
            if k_delivery_reason != deliverreason:
                k_delivery_reason = deliverreason

        for sr in K_Containers:
            axle_damage =  containers['DamageonAxle']
            if k_axle_dam != axle_damage:
                k_axle_dam = axle_damage

        for sr in K_Containers:
            body_damage = containers ['DamageonBody']
            if k_damage_body != body_damage:
                k_damage_body = body_damage

        for sr in K_Containers:
            lid_damage = containers ['DamageonLid']
            if k_damage_lid != lid_damage:
                k_damage_lid = lid_damage

        for sr in K_Containers:
            wheel_damage = containers ['DamageonWheels']
            if k_wheel_dam != wheel_damage:
                k_damage_lid = wheel_damage

        for sr in K_Containers:
            uid =  containers ['Name']
            if k_uid != uid:
                k_uid = uid

    except:
        print ("Pass")



    print k_uid

Output: 输出:

061720150722162744
061720150722162744

Desired Output: 所需输出:

061720150722162721
061720150722162722
061720150722162743
061720150722162744

The issue is that your current k_uid variable and print k_uid command are outside a container loop that cycles through the containers. 问题是您当前的k_uid变量和print k_uid命令在循环遍历容器的容器循环之外。

To print your desired output, you need a loop like the following: 要打印所需的输出,您需要如下所示的循环:

for container in K_Containers['La311Containers']:
    print container['Name']

In a stand-alone context from your other loops this would be like: 在其他循环的独立上下文中,这将是:

K_Containers = CSdata['SRData']['ListOfLa311Containers']
for CSData in K_Containers
    for container in K_Containers['La311Containers']:
        print container['Name']

Another approach is to create a k_uids array and append each k_uid value on to it so you can access them all at the end. 另一种方法是创建一个k_uids数组,并将每个k_uid值附加到该数组上,以便最后可以访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM