【问题标题】:All elements of dictionary showing as type string in Python字典的所有元素在 Python 中显示为类型字符串
【发布时间】:2021-12-20 01:51:31
【问题描述】:

我正在尝试从 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']是字符串类型的。

【问题讨论】:

    标签: python json string dictionary request


    【解决方案1】:
    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'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      相关资源
      最近更新 更多