Problem:
我很难从ups获取一些信息。shipToAddress部分中的城市和州
以下是我从ups网站上获取的易于阅读格式的数据:
Data:
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,
}}]}
Code:
data = response.text
addressinfo =json.loads(data)['trackDetails']['shipToAddress']
for entry in addressinfo:
city = (entry['city'])
state = (entry['state'])
country = (entry['country'])
My Expected Results:
城市='海洋'
状态='NJ'
等等
this is error:
addressinfo=json.loads(data2)['trackDetails']['shipToAddress']
TypeError:列表索引必须是整数或片,而不是str
请注意JSON的格式:
您试图索引到的dict实际上包含在一个列表中(注意方括号)。访问
shipToAddress
字段的正确方法是:而不是你在做什么
当您返回
data = response.text
时,您应该改为执行data = response.json()
,因为它是一个json。这将允许您像json一样访问它。相反,您将它转换为一个带有.text
的字符串,然后尝试将它加载回不需要的字符串中然后访问城市:
相关问题 更多 >
编程相关推荐