Я пытаюсь импортировать 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"
}
]