Ive got a script written to fetch data from an API, and return it, but now i need to parse that data, this is an example of what the json data looks like, with some of the dicti
Ok, looking at the online docs for the requests module, I see that calling r.json()
will do the JSON parsing for you, and give you back a Python dict. The thing you are posting is the output of that dict, so the JSON part has already been taken care of for you.
This code should work in both Python 2 and Python 3, once you have extracted the data to json_response using json_response = r.json()
:
extracted_values = []
json_data = json_response['results']
for item in json_data:
subitem_dict = {}
for key in 'twitter_id office'.split():
subitem_dict[key] = item.get(key) # will give None if key does not exist
extracted_values.append(subitem_dict)
print(extracted_values)
prints:
[{'twitter_id': 'RepToddYoung', 'office': '1007 Longworth House Office Building'},
{'twitter_id': 'SenDonnelly', 'office': '720 Hart Senate Office Building'},
{'twitter_id': 'SenDanCoats', 'office': '493 Russell Senate Office Building'}]