【问题标题】:TypeError: string indices must be integers in complex json arrayTypeError:字符串索引必须是复杂 json 数组中的整数
【发布时间】:2019-12-29 03:27:46
【问题描述】:

将 json 数组转换为对象列表时出现 TypeError。 我试图通过谷歌找到解决方案,但到目前为止还没有运气。 有人可以帮帮我吗? 我得到的错误是:TypeError:字符串索引必须是整数

这是我目前得到的代码:

import json
import urllib.request

with urllib.request.urlopen("https://storage.googleapis.com/osb-exchange/summary.json") as url:
    response = url.read()
data = json.loads(response)
item_list = []

for item in data:
    item_details = {'id': None, 'name': None, 'store_price': None, 'buy_average': None, 'sell_average': None,
                    'buy_quantity': None,'sell_quantity': None, 'overall_average': None, 'overall_quantity': None}
    print(item)
    item_details['id'] = item['id']
    item_details['name'] = item['name']
    item_details['store_price'] = item['store_price']
    item_details['buy_average'] = item['buy_average']
    item_details['sell_average'] = item['sell_average']
    item_details['buy_quantity'] = item['buy_quantity']
    item_details['sell_quantity'] = item['sell_quantity']
    item_details['overall_average'] = item['overall_average']
    item_details['overall_quantity'] = item['overall_quantity']
    item_list.append(item_details)
print(item_list)

【问题讨论】:

  • @khelwood 我的坏了,现在应该没事了
  • @Barmar 所以它确实是一个字符串,我该如何正确使用它?
  • 为什么需要那个循环?您只是将字典列表复制到相同的字典列表中。为什么不只是item_list = json.loads(response)
  • JSON 中也没有 store_price 元素。
  • 除此之外,您只是在复制除members 之外的所有内容。

标签: python json type-conversion typeerror


【解决方案1】:

data 是一个字典。当您使用for item in data: 遍历字典时,它会遍历字典键,而不是值。使用

for item in data.values():

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 2022-07-22
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多