从 JSON 中提取信息

2024-10-02 20:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: nonefalsecitydatacmscountryeodstate
2条回答

请注意JSON的格式:

'trackDetails': [{
    ...
    'shipToAddress': {...}
}]

您试图索引到的dict实际上包含在一个列表中(注意方括号)。访问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']

相关问题 更多 >