I am trying to parse a json response from an api request in Python which is a dictionary containing various types including nested dictionaries, arrays, and strings. But when I try to iterate over the values of a nested dictionary or array, it says the object is of type string and has no values.
import requests
import json
def clean_data():
r = requests.get('https://coderbyte.com/api/challenges/json/json-cleaning')
Data = r.json()
for data in Data['name']:
while '' in data.values():
del data[list(data.keys())[list(data.values()).index('')]]
return Data
print(clean_data())
I expect this to print:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}
But I get an error AttributeError: 'str' object has no attribute 'values'
And when I debug, I indeed find that Data['name']
is of type string.
CodePudding user response:
import requests
import json
def clean_data():
r = requests.get('https://coderbyte.com/api/challenges/json/json-cleaning')
Data = r.json()
for data in list(Data['name']):
if Data['name'][data] == '':
Data['name'].pop(data)
return Data
print(clean_data())
With this solution, the output would be:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}