执行后得到以下响应 res_res = response.json() 我在下面提到了带有2个对象的示例输出,而实际输出中有更多对象
{'restaurants': [{'restaurant':'R': {'has_menu_status': {'delivery': -1,
'takeaway': -1}},
'all_reviews_count': 8,
'average_cost_for_two': 350,
'book_again_url': '',
'book_form_web_view_url': '',
'cuisines': 'Momos, Chinese, Fast Food',
'name': 'Mumbai Masala'
'user_rating': {'aggregate_rating': '3.2',
'rating_color': 'CDD614',
'rating_obj': {'bg_color': {'tint': '500',
'type': 'lime'},
'title': {'text': '3.2'}},
'rating_text': 'Average',
'votes': '9'}}},
{'restaurant':'R': {'has_menu_status': {'delivery': -1,
'takeaway': -1}},
'all_reviews_count': 4,
'average_cost_for_two': 300,
'book_again_url': '',
'book_form_web_view_url': '',
'cuisines': 'Fast Food',
'name' : 'Jumbo King',
'user_rating': {'aggregate_rating': '3.4',
'rating_color': 'CDD614',
'rating_obj': {'bg_color': {'tint': '500',
'type': 'lime'},
'title': {'text': '3.4'}},
'rating_text': 'Average',
'votes': '7'}}}],
'results_found': 48,
'results_shown': 20,
'results_start': 0}
我想从每个对象中提取仅average_cost_for_two和名称并将其存储在单独的列表中。任何人都可以帮助我如何迭代我得到的json响应并获得所需的输出。提前谢谢!!!
答案 0 :(得分:1)
要将结果存储在单独的列表(我假设是字典列表)中,请执行以下操作:
import json
test = json.loads(test_json) # It is your json from response
separate_list = [{'name': rest['restaurant']['name'], 'average_cost_for_two': rest['restaurant']['average_cost_for_two']}
for rest in test['restaurants']]
然后列表将如下所示:
[{'name': 'Mumbai Masala', 'average_cost_for_two': 350},
{'name': 'Jumbo King', 'average_cost_for_two': 300}]
您可以迭代和访问这样的元素:
for element in separate_list:
print(element['name'])
print(element['average_cost_for_two'])