Answer the question
In order to leave comments, you need to log in
How to properly expand complex json in python?
I work with the VKontakte API. I write in Python. I received a json response to my request. I can't unpack it. Tried through nested for loops, through list generators -
it doesn't work normally. The point is that data groups come in the json response - i.e. a set of data for each object. For example, a person, his contact details and some information. I need
to expand the json so that at the end I get a group of lists of these contacts, for example:
['id_1', 'telefon_1', 'e-mail_1']
['id_2', 'telefon_2', 'e-mail_2']
[' id_3', 'telefon_3', 'e-mail_3']
etc.
But for now I can only get everything en masse:
['id_1', 'telefon_1', 'e-mail_1', 'id_2',
Which makes it impossible to separate these people and process the data of specific people.
Here is the json itself:
[{'lead_id': '756644', 'user_id': '1015455', 'date': '159565554', 'answers':
[{'key': 'first_name', 'answer':
{'value':
'Alex'}},
{'key': 'email', 'answer':
{'value':
'[email protected]'}},
{'key': 'phone_number', 'answer':
{'value':
'+79864567253'}}]},
{'lead_id': '756664', 'user_id': '1016766', 'date': '1595643427', 'answers':
[{'key': 'first_name', 'answer':
{'value':
'Al'}},
{'key': 'email', 'answer':
{'value':
'[email protected]'}},
{'key': 'phone_number', 'answer':
{'value':
'+7 (999) 3965533'}}]}]
Answer the question
In order to leave comments, you need to log in
It's better to use dictionaries, of course
data = [{'lead_id': '756644', 'user_id': '1015455', 'date': '159565554', 'answers':
[{'key': 'first_name', 'answer':
{'value':
'Alex'}},
{'key': 'email', 'answer':
{'value':
'[email protected]'}},
{'key': 'phone_number', 'answer':
{'value':
'+79864567253'}}]},
{'lead_id': '756664', 'user_id': '1016766', 'date': '1595643427', 'answers':
[{'key': 'first_name', 'answer':
{'value':
'Al'}},
{'key': 'email', 'answer':
{'value':
'[email protected]'}},
{'key': 'phone_number', 'answer':
{'value':
'+7 (999) 3965533'}}]}]
all_info = []
for member in data:
member_info = []
member_info.append(member['lead_id'])
answers = member['answers']
for answer in answers:
answer_key = answer.get('key', None)
if answer_key == 'phone_number':
member_info.insert(1, answer['answer']['value'])
elif answer_key == 'email':
member_info.insert(2, answer['answer']['value'])
all_info.append(member_info)
print(all_info)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question