首页 > 解决方案 > 字符串索引必须是整数 json

问题描述

我有一个 json 数据https://steamcommunity.com/id/RednelssGames/inventory/json/730/2 需要获取所有项目的名称

r = requests.get('https://steamcommunity.com/id/RednelssGames/inventory/json/730/2')
if r.json()['success'] == True:
     for rows in r.json()['rgDescriptions']:
         print(rows['market_hash_name'])

获取错误字符串索引必须是整数

标签: python

解决方案


从您提供的链接:

"rgDescriptions":{"4291220570_302028390":

rgDescriptions不返回数组,而是一个对象(在本例中为字典)(注意左大括号 ( {) 而不是常规方括号 ( [))。

通过使用for rows in r.json()['rgDescriptions']:,您最终会遍历字典的键。字典的第一个键似乎是"4291220570_302028390",它是一个字符串。

所以当你这样做时print(rows['market_hash_name']),你试图访问'market_hash_name'你的对象的“索引” rows,但rows实际上是一个字符串,所以它不起作用。


推荐阅读