无法在Python中访问嵌套的JSON数据

时间:2018-09-26 17:02:36

标签: python json rest

我正在尝试使用Americommerce API为客户赢得名字。除了尝试访问返回first_name

KeyError: customer以外,我有下面的代码有效

由于first_name嵌套在customer下,因此我在访问它时遇到了问题。 order_date没问题,但是当我尝试使用first_name的当前功能时:

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

我不明白如何嵌套这些

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输出:

    {
        "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",

        }
}

1 个答案:

答案 0 :(得分:0)

该错误表明并非每个订单都有一个customer字段。因此,您需要检查一下。

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