问题:
我无法提取一些信息。 shipToAddress部分中的城市和州。
下面是一个易于阅读的格式的数据,我将从ups网站提取请求:
数据:
data = {
'statusCode': '200',
'statusText': 'Successful',
'isLoggedInUser': False,
'trackedDateTime': '04/16/2019 1:33 P.M. EST',
'isBcdnMultiView': False,
'trackDetails': [{
'errorCode': None,
'errorText': None,
'requestedTrackingNumber': '1Z3774E8YN99957400',
'trackingNumber': '1Z3774E8YN99957400',
'isMobileDevice': False,
'packageStatus': 'Loaded on Delivery Vehicle',
'packageStatusType': 'I',
'packageStatusCode': '072',
'progressBarType': 'InTransit',
'progressBarPercentage': '90',
'simplifiedText': '',
'scheduledDeliveryDayCMSKey': 'cms.stapp.tue',
'scheduledDeliveryDate': '04/16/2019',
'noEstimatedDeliveryDateLabel': None,
'scheduledDeliveryTime': 'cms.stapp.eod',
'scheduledDeliveryTimeEODLabel': 'cms.stapp.eod',
'packageCommitedTime': '',
'endOfDayResCMSKey': None,
'deliveredDayCMSKey': '',
'deliveredDate': '',
'deliveredTime': '',
'receivedBy': '',
'leaveAt': None,
'leftAt': '',
'shipToAddress': {
'streetAddress1': '',
'streetAddress2': '',
'streetAddress3': '',
'city': 'OCEAN',
'state': 'NJ',
'province': None,
'country': 'US',
'zipCode': '',
'companyName': '',
'attentionName': '',
'isAddressCorrected': False,
'isReturnAddress': False,
'isHoldAddress': False,
}}]}
码:
data = response.text
addressinfo =json.loads(data)['trackDetails']['shipToAddress']
for entry in addressinfo:
city = (entry['city'])
state = (entry['state'])
country = (entry['country'])
我的预期结果:
city ='海洋'
state ='NJ'
等等
这是错误:
addressinfo = json.loads(data2)['trackDetails'] ['shipToAddress']
TypeError:list indices必须是整数或切片,而不是str
请注意您的JSON格式:
'trackDetails': [{
...
'shipToAddress': {...}
}]
您尝试索引的字典实际上包含在列表中(注意方括号)。访问shipToAddress
字段的正确方法是这样做:
addressinfo = json.loads(data2)['trackDetails'][0]['shipToAddress']
^^^
而不是你在做什么。
当你返回data = response.text
时,你应该做data = response.json()
,因为它是一个json。这将允许您像json一样访问它。相反,您将它转换为带有.text
的字符串,然后尝试将其加载回来,而不是必需的。
然后访问城市:
city = data['trackDetails'][0]['shipToAddress']['city']
state = data['trackDetails'][0]['shipToAddress']['state']