【问题标题】:Trouble accessing nested JSON data in Python在 Python 中访问嵌套 JSON 数据时遇到问题
【发布时间】:2019-03-02 12:46:20
【问题描述】:

我正在尝试使用 americommerce api 获取客户的名字。我有以下代码有效,除非我尝试访问返回KeyError: customerfirst_name

因为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",

        }
}

【问题讨论】:

  • 是否有可能没有为所有人填写客户字段?
  • 尝试result["customer"].get("first_name"),如果该客户不存在该字段,则返回None。虽然如果您正在处理客户列表,那么它将类似于result[i]["customer"]...

标签: python json rest


【解决方案1】:

该错误表明并非每个订单都有customer 字段。所以你需要检查一下。

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

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多