0

Почему последняя строчка выдаёт ошибку и как её исправить?

import requests
import json

url = 'https://api.color.pizza/v1/212121'
response = requests.get(url)
json_data = json.loads(response.text)['colors']

print('API Response:\n', json.dumps(json_data, indent=4))
name = json_data['name']

Вывод:

[
    {
        "name": "Lead",
        "hex": "#212121",
        "rgb": {
            "r": 33,
            "g": 33,
            "b": 33
        },
        "hsl": {
            "h": 0,
            "s": 0,
            "l": 12.941176470588237
        },
        "luminance": 22.062320231562225,
        "requestedHex": "#212121",
        "distance": 0
    }
]

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 9, in <module>
TypeError: list indices must be integers or slices, not str

[Program finished]

1
  • Текст ошибки перевести смогли? Он Вам понятен? 20 дек 2020 в 20:43

1 ответ 1

4

потому что у вас в json_data лежит не словарь, а список в котором один элемент. Вам надо получить первый элемент этого списка

json_data = json.loads(response.text)['colors'][0]

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.