Python 中显示为字符串类型的字典的所有元素
All elements of dictionary showing as type string in Python
我正在尝试解析 Python 中 api 请求的 json 响应,这是一个包含各种类型的字典,包括嵌套字典、数组和字符串。但是当我尝试遍历嵌套字典或数组的值时,它说对象是字符串类型并且没有值。
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())
我希望打印出来:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}
但是我得到一个错误AttributeError: 'str' object has no attribute 'values'
而我调试的时候,确实发现Data['name']
是string类型。
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())
使用此解决方案,输出 将是:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}
我正在尝试解析 Python 中 api 请求的 json 响应,这是一个包含各种类型的字典,包括嵌套字典、数组和字符串。但是当我尝试遍历嵌套字典或数组的值时,它说对象是字符串类型并且没有值。
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())
我希望打印出来:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}
但是我得到一个错误AttributeError: 'str' object has no attribute 'values'
而我调试的时候,确实发现Data['name']
是string类型。
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())
使用此解决方案,输出 将是:
{'name': {'first': 'Robert', 'last': 'Smith'}, 'age': 25, 'DOB': '-', 'hobbies': ['running', 'coding', '-'], 'education': {'highschool': 'N/A', 'college': 'Yale'}}