Ошибка TypeEr: списочные индексы должны быть целыми или кусочками, а не str для некоторых JSON, но не для всех? - PullRequest
0 голосов
/ 24 сентября 2019

Я пытаюсь импортировать id из файла JSON, но квадратные скобки в начале / конце файла JSON для второго JSON приводят к его разрыву.Вот код, который мне нужно получить id из файлов json:

import requests

url = 'http://benbotfn.tk:8080/api/cosmetics/search'

params = dict(
    displayName='renegade raider',
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

json_id = data['id']

print(json_id)

Этот код работает для любых файлов JSON, которые не начинаются / не заканчиваются в квадратных скобках.


Но когда я изменяю URL JSON на: http://benbotfn.tk:8080/api/cosmetics/search/multiple и запускаю тот же код, я получаю эту ошибку:

Traceback (most recent call last):
  File "apigrabber.py", line 12, in <module>
    json_id = data['id']
TypeError: list indices must be integers or slices, not str


Чтобы попытаться это исправить, я попыталсяпреобразовать data в строку, чтобы я мог снять квадратную скобку, используя этот код:

import requests

url = 'http://benbotfn.tk:8080/api/cosmetics/search/multiple'

params = dict(
    displayName='renegade raider',
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

nosquares = str(data).replace('[','').replace(']','')
json_id = nosquares['id']

print(nosquares)


Но затем я получаю ошибку:

Traceback (most recent call last):
  File "apigrabber.py", line 13, in <module>
    json_id = nosquares['id']
TypeError: string indices must be integers

Есть лиВ любом случае, я могу исправить первоначальную ошибку (list indices must be integers or slices, not str), не преобразовывая ее в строку?

print (data) по запросу (raw):

[{"displayName":"Renegade Raider","backendType":"AthenaCharacter","icon":"http://benbotfn.tk:7071/static/AthenaCharacter/cid_028_athena_commando_f.png","description":"Rare renegade raider outfit.","backendRarity":"EFortRarity::Rare","gameplay_tags":["Cosmetics.Source.Season1.SeasonShop","Cosmetics.Set.StormScavenger","Cosmetics.UserFacingFlags.HasVariants"],"variants":{"STYLE":[{"name":"DEFAULT","icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Athena/Soldier/T-Soldier-HID-028-Athena-Commando-F.T-Soldier-HID-028-Athena-Commando-F.png"},{"name":"CHECKERED","icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Variants/T-Variant-F-RenegadeRaider-Variant.T-Variant-F-RenegadeRaider-Variant.png"}]},"id":"CID_028_Athena_Commando_F","type":"Outfit","rarity":"Rare"}]

print (data) - по запросу (отформатировано):

[
   {
      "displayName":"Renegade Raider",
      "backendType":"AthenaCharacter",
      "icon":"http://benbotfn.tk:7071/static/AthenaCharacter/cid_028_athena_commando_f.png",
      "description":"Rare renegade raider outfit.",
      "backendRarity":"EFortRarity::Rare",
      "gameplay_tags":[
         "Cosmetics.Source.Season1.SeasonShop",
         "Cosmetics.Set.StormScavenger",
         "Cosmetics.UserFacingFlags.HasVariants"
      ],
      "variants":{
         "STYLE":[
            {
               "name":"DEFAULT",
               "icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Athena/Soldier/T-Soldier-HID-028-Athena-Commando-F.T-Soldier-HID-028-Athena-Commando-F.png"
            },
            {
               "name":"CHECKERED",
               "icon":"http://benbotfn.tk:7071/static/CosmeticVariants/Game/UI/Foundation/Textures/Icons/Heroes/Variants/T-Variant-F-RenegadeRaider-Variant.T-Variant-F-RenegadeRaider-Variant.png"
            }
         ]
      },
      "id":"CID_028_Athena_Commando_F",
      "type":"Outfit",
      "rarity":"Rare"
   }
]

1 Ответ

1 голос
/ 25 сентября 2019

Когда вы получаете список, вам нужно будет получить id, проанализировав список (который зависит от того, какой список вы получаете), поэтому поток кода должен быть таким:

....
data = resp.json()
if isinstance(data, dict):
    id = data['id']
else:
    # In this case you are getting list of dictionaries so you
    # may get multiple id's.
    # Response shared by you has only one dictionary in list.
    for d in data:  # Iterate over all dict in list
        print(d['id'])
....

Вы можете собрать все идентификаторы в некотором списке / наборе и использовать позже в программе, в зависимости от вашего запроса.

...