【问题标题】:Creating a dictionary from a json list of arrays从数组的 json 列表创建字典
【发布时间】:2020-01-24 18:43:35
【问题描述】:

我正在尝试从字典列表中创建一个包含特定键值的字典。我相信当我输入 chunkdata.extend(pythondict[0][1][2], chunkdata 时,我的代码不会使字典变平,chunkdata 将返回整个第一个第二和第三个字典,我想要像“名称”键这样的东西对在响应中返回的所有字典。

chunkdata = []
for chunk in chunklist:
    url3 = "some URL"

    headers = {'accept': 'application/json',


    response = requests.request("GET", url3, headers=headers)
    time.sleep(5)
    print(response.text)
    pythondict = json.loads(response.text)
    print(pythondict)

    chunkdata.extend(pythondict['name']['age']['date']

pythondict 输出

[{'data': {'name': 'jon', 'age': '30', 'date': '2020-01-05', 'time': '1', 'color': '蓝色'},{'数据':{'名称':'phil','年龄':'33','日期':'2020-01-05','时间':'1','颜色' : 'blue'}, {'data': {'name': 'ted', 'age': '25', 'date': '2020-01-05', 'time':'1', 'color ': '蓝色'}]

Traceback (most recent call last):
  File line 84, in <module>
    chunkdata.extend(pythondict['name']['age']['date']
TypeError: list indices must be integers or slices, not str

【问题讨论】:

  • print(pythondict) 的输出是什么?
  • print(pythondict) 输出是从 response.text 中的原始 json 转换而来的字典列表
  • 如果我们能看到那些字典就好了...... >
  • ['name']['age']['date'] 之一是列表而不是字典。除此之外,没有人能为您的问题提供更好的答案。

标签: python json python-3.x python-requests


【解决方案1】:

使用requests.json() 进行解析。它更加可靠和准确。

注意:响应标头必须在标头中包含 Content-Type: application/json 才能使 .json() 方法起作用

【讨论】:

    【解决方案2】:

    我发现你得到的 json 格式不在这里。我无法确定每个元素之前的“数据:”的必要性。 最好改成如下形式:

    python_dict=[{'name': 'jon', 'age': '30', 'date': '2020-01-05', 'time': '1', 'color': 'blue' }, {'name': 'phil', 'age': '33', 'date': '2020-01-05', 'time': '1', 'color': 'blue'}, {'姓名:'ted','年龄':'25','日期':'2020-01-05','时间':'1','颜色':'蓝色'}]

    修改相关部分代码如下:

    chunkdata=[]
    for x in range(len(python_dict)):
        temp_list=[python_dict[x]['name'],python_dict[x]['age'],python_dict[x]['date'],python_dict[x]['time'],python_dict[x]['color']]
        chunkdata.append(temp_list)
    print(chunkdata)
    

    chunkdata 将是您可以继续追加的列表列表。 chunkdata 的输出如下:

    [['jon', '30', '2020-01-05', '1', 'blue'], ['phil', '33', '2020-01-05', '1', 'blue'], ['ted', '25', '2020-01-05', '1', 'blue']]

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2020-11-17
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多