简体   繁体   中英

Trouble accessing nested JSON data in Python

I'm trying to get the first name for a customer using americommerce api. I have the following code which works, except when I try to access the first_name which returns KeyError: customer

since first_name is nested under customer I'm having problems accessing it. order_date has no problem but when i try what i have currently for first_name :

 first_name          =result["customer"]["first_name"] or
 first_name          =result["customer"][4]["first_name"] I get an error.

I dont understand how to get these nested

for result in results['orders']:
          order_status_info= self_api.which_api('order_statuses/%d' % result['order_status_id'])
          for customer_blocked_reason in customer_blocked_reasons:
            if customer_blocked_reason in order_status_info['name']:
              customer_is_blocked = True

          order_id            = 0
          order_date          = result['ordered_at']                
          first_name          =result["customer"]["first_name"] 
          print(first_name)

JSON output:

    {
        "id": 123,
        "customer_id": 234,
        "customer_type_id": 0,  
        "ordered_at": "2017-01-21T23:19:00-05:00",    

        "billing_address": {
            "id": 123            
        },
        "shipping_address": {
            "id": 443
        },
        "order_status": {
            "id": 1
        },
        "customer": {
            "id": 123,
            "customer_number": "",
            "last_name": "someguy",
            "first_name": "billie",

        }
}

The error indicates that not every order has a customer field. So you need to check for that.

if 'customer' in result:
    first_name = result['customer']['first_name']
else:
    first_name = 'unknown'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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