如何打印出这个json的客户电子邮件?
如何使用python循环函数访问此json中的客户电子邮件而不获取KeyError?
{
"orders":[
{
"created_at":"2020-06-11T07:56:42-04:00",
"customer":{
"id":3684055154844,
"email":"xxxxxxx@gmail.com",
"accepts_marketing":False,
"created_at":"2020-06-10T15:51:50-04:00",
"updated_at":"2020-06-11T07:56:42-04:00",
"first_name":"xxx",
"last_name":"xxxxx",
"orders_count":1,
"state":"disabled",
"total_spent":"1160.00",
"last_order_id":2501429756060,
"note":"None",
"verified_email":True,
"multipass_identifier":"None",
"tax_exempt":False,
"phone":"None",
"tags":"",
"last_order_name":"#1005",
"currency":"xxx",
"accepts_marketing_updated_at":"2020-06-10T15:51:50-04:00",
"marketing_opt_in_level":"None",
"admin_graphql_api_id":"gid",
"default_address":{
"id":4397679181980,
"customer_id":3684055154844,
"first_name":"xxxx",
"last_name":"xxxxxx",
"company":"None",
"address1":"14",
"address2":"",
"city":"N",
"province":"None",
"country":"K",
"zip":"0217",
"phone":"None",
"name":"J",
"province_code":"None",
"country_code":"E",
"country_name":"K",
"default":True
}
}
},我的代码python循环
if response.status_code == 200:
products = json.loads(response.text)
print(products)
for order in products['orders']:
created_at = order['created_at']
customer_total_spent = order['customer']['email']
print('order_created_date', created_at)
print('customer_email', email)运行这段代码后,我得到了这个错误# customer_orders_count = order'customer‘KeyError:'customer'
发布于 2020-06-12 07:56:58
您需要处理json可能不包含所需密钥的情况:
您可以添加一个if条件来检查json中的键:
for order in products['orders']:
if 'customer' in order:
created_at = order['created_at']
customer_total_spent = order['customer']['email']
print(customer_total_spent)
print('order_created_date', created_at)
print('customer_email', email)或
您可以使用get()方法在循环时避免任何键错误:
for order in products['orders']:
created_at = order.get('created_at', '')
customer = order.get('customer', '')
customer_total_spent = customer.get('email', '')
print(customer_total_spent)
print('order_created_date', created_at)
print('customer_email', email)这将得到键的值,如果找到,它将返回一个空字符串,并且不会抛出错误。
https://stackoverflow.com/questions/62339738
复制相似问题