【发布时间】:2019-03-02 12:46:20
【问题描述】:
我正在尝试使用 americommerce api 获取客户的名字。我有以下代码有效,除非我尝试访问返回KeyError: customer的first_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"]...