如何循环多级JSON对象

时间:2015-02-25 01:21:07

标签: python json

我有一个将JSON Web服务写入地理数据库的脚本。 JSON服务最多可以有10个"电子废物"对象,3如下所示。我能够到达这里因为我已经知道数据是如何构建的,即指标等。

我想编写我的脚本,以便我可以循环并只写入具有值的字段到我的数据库。因此,如果有10个电子垃圾项目,我会遍历电子垃圾并在我的数据库中抓取我想要的项目,现在我通过索引获取数据。

   "La311ElectronicWaste": [
                            {
                                "CollectionLocation": "Gated Community/Multifamily Dw",
                                "DriverFirstName": "",
                                "DriverLastName": "",
                                "ElectronicWestType": "Microwaves",
                                "GatedCommunityMultifamilyDwelling": "Curb",
                                "IllegallyDumped": "N",
                                "ItemCount": "3",
                                "MobileHomeSpace": "",
                                "OtherElectronicWestType": "",
                                "ServiceDateRendered": "",
                                "TruckNo": "",
                                "Type": "Electronic Waste",
                                "IllegalDumpCollectionLoc": "",
                                "LastUpdatedBy": "",
                                "Name": "021720151654176711"
                            },
                            {
                                "CollectionLocation": "Gated Community/Multifamily Dw",
                                "DriverFirstName": "",
                                "DriverLastName": "",
                                "ElectronicWestType": "Televisions (Any Size)",
                                "GatedCommunityMultifamilyDwelling": "Curb",
                                "IllegallyDumped": "N",
                                "ItemCount": "6",
                                "MobileHomeSpace": "",
                                "OtherElectronicWestType": "",
                                "ServiceDateRendered": "",
                                "TruckNo": "",
                                "Type": "Electronic Waste",
                                "IllegalDumpCollectionLoc": "",
                                "LastUpdatedBy": "",
                                "Name": "021720151654176722"
                            },
                            {
                                "CollectionLocation": "Gated Community/Multifamily Dw",
                                "DriverFirstName": "",
                                "DriverLastName": "",
                                "ElectronicWestType": "VCR/DVD Players",
                                "GatedCommunityMultifamilyDwelling": "Curb",
                                "IllegallyDumped": "N",
                                "ItemCount": "1",
                                "MobileHomeSpace": "",
                                "OtherElectronicWestType": "",
                                "ServiceDateRendered": "",
                                "TruckNo": "",
                                "Type": "Electronic Waste",
                                "IllegalDumpCollectionLoc": "",
                                "LastUpdatedBy": "",
                                "Name": "021720151654176723"
                            }
                        ]
                    },

代码示例:

f2 = open('C:\Users\Administrator\Desktop\DetailView.json', 'r')

data2 = jsonpickle.encode( jsonpickle.decode(f2.read()) )

url2 = "myURL"
headers2 = {'Content-type': 'text/plain', 'Accept': '/'}

r2 = requests.post(url2, data=data2, headers=headers2)

decoded2 = json.loads(r2.text)















SRAddress = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['SRAddress']
latitude = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['Latitude']
longitude = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['Longitude']

CommodityType = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][0]['Type']
ItemType = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][0]['ElectronicWestType']
ItemCount_1 = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][0]['ItemCount']


CommodityType1 = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][1]['Type']
ItemType1 = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][1]['ElectronicWestType']
ItemCount1 = decoded['Response']['ListOfServiceRequest']['ServiceRequest'][0]['ListOfLa311ElectronicWaste']['La311ElectronicWaste'][1]['ItemCount']








print SRAddress
print latitude
print longitude

print CommodityType
print ItemType
print ItemCount_1






print CommodityType1
print ItemType1
print ItemCount1


Items and Keys should maintain same order
item ={'SRAddress': SRAddress,  'CommodityType': CommodityType, 'ItemType': ItemType, 'ItemCount_1': ItemCount_1, 'longitude': longitude, 'latitude': latitude}
import numpy as np     #NOTE THIS
keys = ['SRAddress','CommodityType', 'ItemType','ItemCount_1','longitude','latitude']
k1,k2,k3, k4, k5, k6 = keys
# data_line ={'SRAddress': SRAddress, 'Longitude': longitude, 'Latitude': latitude, 'CommodityType': CommodityType, 'ItemCount': ItemCount}
frmt = '\nStraight dictionary output\n Address: {} Long: {} Lat: {}'
print(frmt.format(item[k1],item[k2],item[k3], item[k4],item[k5], item[k6]))
print '\noption 1:  List comprehension with unicode'
a =  tuple([unicode(item[key]) for key in keys])  # list comprehension with unicode
print('{}'.format(a))
dt = np.dtype([('SRAddress','U40'),('CommodityType','U40'), ('ItemType','U40'), ('ItemCount_1','U40'),('longitude','<f8'),('latitude','<f8')])
arr = np.array(a,dtype=dt)

print'\narray unicode\n',arr
print'dtype',arr.dtype
print '\noption 2:List comprehension without unicode'
b = tuple([item[key] for key in keys])
print('{}'.format(b))
dt = np.dtype([('SRAddress','U40'),('CommodityType','S4'), ('ItemCount','U40'),('longitude','<f8'),('latitude','<f8')])
arr = np.array(b,dtype=dt)
print'\narray without unicode\n',arr
print'dtype',arr.dtype

arcpy.da.NumPyArrayToFeatureClass(arr, fc, ['longitude', 'latitude'], sr)

print json.dumps(decoded, sort_keys=True, indent=4)

1 个答案:

答案 0 :(得分:0)

您可以随时循环键。

一个例子:

decoded = {'La311ElectronicWaste':{'SRAddress':'123 my street'},
           'La31ElectronicWaste':{'ItemType':'computer',
                                  'no data':''},
           'other':'cool',
           }

subdict = {}

for key in decoded:
    if 'ElectronicWaste' in key:
        subdict[key] = {}
        for entry, item in decoded[key].items():
            if item:
                subdict[key][entry] = decoded[key][entry]