我正在尝试清理数据以进行分析
这是JSON示例
response.json() = [{'count': 19804,
'next': {'limit': 1, 'offset': 1},
'previous': None,
'results':
[{'id': '334455',
'custom_id': '112',
'company': 28,
'company_name': 'Sunshine and Flowers',
'delivery_address': '34 olive beach house, #01-22, 612345',
'delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'},
'sender_name': 'Edward Shine',
'sender_email': '',
'sender_contact': '91234567',
'removed': None,
'recipient_name': 'Mint Shine',
'recipient_contact': '91234567',
'notes': '',
'items': [{'id': 21668, 'name': 'Loose hair flowers', 'quantity': 1, 'metadata': {}, 'removed': None}, {'id': 21667, 'name': "Groom's Boutonniere", 'quantity': 1, 'metadata': {}, 'removed': None}, {'id': 21666, 'name': 'Bridal Bouquet', 'quantity': 1, 'metadata': {}, 'removed': None}],
'latitude': '1.28283838383642000000',
'longitude': '103.2828037266201000000',
'created': '2019-08-15T05:40:30.385467Z',
'updated': '2019-08-15T05:41:27.930110Z',
'status': 'pending',
'verbose_status': 'Pending',
'logs': [{'id': 334455, 'order': '50c402d8-7c76-45b5-b883-e2fb887a507e', 'order_custom_id': '112', 'order_delivery_address': '34 olive beach house, #01-22, 6123458', 'order_delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'}, 'message': 'Order was created.', 'failure_reason': None, 'success_code': None, 'success_description': None, 'created': '2019-08-15T05:40:30.431790Z', 'removed': None}, {'id': 334455, 'order': '50c402d8-7c76-45b5-b883-e2fb887a507e', 'order_custom_id': '112', 'order_delivery_address': '34 olive beach house, #01-22, 612345', 'order_delivery_timeslot': {'lower': '2019-12-06T10:00:00Z', 'upper': '2019-12-06T13:00:00Z', 'bounds': '[)'}, 'message': 'Order is pending.', 'failure_reason': None, 'success_code': None, 'success_description': None, 'created': '2019-08-15T05:40:30.433139Z', 'removed': None}],
'reschedule_requests': [],
'signature': None}]]
我已经尝试过此代码,并且可以正常工作,它会相应删除指定的内容。
data = response.json()
del data['count']
del data['next']
del data['previous']
del data['results'][0]['logs']
print(data)
但是当我尝试删除“项目”(我只希望保留“名称”)时,它不起作用。
这是我的代码,用于删除“名称”中除“名称”之外的所有内容
del data['results'][0]['items']['id']['quantity']['metadata']['removed']
我想要的输出是:
'items':
[{'name': 'Loose hair flowers'},
{''name': "Groom's Boutonniere"},
{'name': 'Bridal Bouquet'}]
我该怎么做?
答案 0 :(得分:0)
无需从JSON响应中删除数据,只需迭代JSON响应并使用列表推导即可获取商品数据。
例如。
items = [{'name' :x['name']} for x in data[0]['results'][0]['items']]
print(items)
O / P:
[{'name': 'Loose hair flowers'}, {'name': "Groom's Boutonniere"},
{'name': 'Bridal Bouquet'}]
或者,如果您想更改响应并且项目仅保留预期的输出数据,请重新分配它。
data[0]['results'][0]['items'] = items