简体   繁体   English

字符串索引必须是整数 json

[英]string indices must be integers json

i have a json data https://steamcommunity.com/id/RednelssGames/inventory/json/730/2 need get names of all the items我有一个 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'])

getting error string indices must be integers获取错误字符串索引必须是整数

From the link you provided:从您提供的链接:

"rgDescriptions":{"4291220570_302028390":

rgDescriptions doesn't return an array, but an object (a dictionary, in this case) (notice the opening curly brace ( { ) rather than a regular square brace ( [ )). rgDescriptions不返回一个数组,而是一个 object(在本例中为字典)(注意左大括号 ( { ) 而不是常规方括号 ( [ ))。

By using for rows in r.json()['rgDescriptions']: you end up iterating over the dictionary's keys.通过使用for rows in r.json()['rgDescriptions']:您最终会遍历字典的键。 The first key of the dictionary seems to be "4291220570_302028390" , which is a string.字典的第一个键似乎是"4291220570_302028390" ,它是一个字符串。

so when you do print(rows['market_hash_name']) , you're attempting to access the 'market_hash_name' "index" of your rows object, but rows is actually a string, so it doesn't work.因此,当您执行print(rows['market_hash_name'])时,您正在尝试访问rows object 的'market_hash_name' “索引”,但rows实际上是一个字符串,因此它不起作用。

Change the for-loop as follows:更改 for 循环如下:

                for rows in r.json()['rgDescriptions'].values():
                    print(rows['market_hash_name'])

By iterating over a dictionary like you did, you get the keys and not the values (rows).通过像您一样遍历字典,您将获得而不是值(行)。 If you want to iterate over the values, you have to iterate over the return value of dict.values() .如果要迭代值,则必须迭代dict.values()的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM