【问题标题】:How to write an if statement using == for data loaded as json loads如何使用 == 为 json 加载时加载的数据编写 if 语句
【发布时间】:2021-10-16 20:45:53
【问题描述】:

这段代码我写过,修改了很多次,不知道为什么不行。

蟒蛇

while True:
    headers = {'client-id': twitch_Client_ID, 'Authorization': authorization}
    response_channel = requests.get('https://api.twitch.tv/helix/streams?user_login=' + twitchID, headers=headers)
    print(response_channel.text)

    try:
        if loads(response_channel.text)['data'][0]['type'] == 'live' and check == False:
            title = loads(response_channel.text)['data'][0]['title']
            game_name = loads(response_channel.text)['data'][0]['game_name']
            username = loads(response_channel.text)['data'][0]['user_name']
            thumbnail = 'https://static-cdn.jtvnw.net/previews-ttv/live_user_scw1101-1920x1080.jpg'

            twitch_embed = discord.Embed(title=title , description="\n 방송보러가기 : https://www.twitch.tv/scw1101")
            twitch_embed.add_field(name="스트리머", value=username, inline=True)
            twitch_embed.add_field(name="게임 이름", value=game_name, inline=True)
            twitch_embed.set_thumbnail(url=thumbnail)
            await channel.send("<@everyone> 오뱅온~", embeds=twitch_embed)
            print("Online")
            check = True
    except:
        print("Offline")
        check = False

    await asyncio.sleep(5)

json

{
    "data": [{
        "id": "39807966251",
        "user_id": "119609287",
        "user_login": "bboyul",
        "user_name": "뽀율",
        "game_id": "19620578",
        "game_name": "Super People",
        "type": "live",
        "title": "입 딜 은 세 계 최 강 !(︶^︶)ノ",
        "viewer_count": 14,
        "started_at": "2021-08-13T13:02:23Z",
        "language": "ko",
        "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_bboyul-{width}x{height}.jpg",
        "tag_ids": ["ab2975e3-b9ca-4b1a-a93e-fb61a5d5c3a4"],
        "is_mature": false
    }],
    "pagination": {}
}

我正在使用 discord.py 制作一个 twitch 实时通知机器人。但是,这很困难,因为韩国的数据不多。请帮忙

编辑

json 响应来了,print("offline") 工作,即使数据类型是实时的,通知不起作用

【问题讨论】:

  • 不要反复拨打loads(response_channel.text)。将 JSON 加载到变量中一次,然后引用它。

标签: python json discord.py


【解决方案1】:

不仅加载,使用 json.loads 并保存结果。

response_json = json.loads(response_channel.text) 
if response_json['data'][0]['type'] == 'live' and check == False:

【讨论】:

  • 我的理解是他已经在使用json.loads,但是从模块中导入了函数,省略了
  • 是的,注意导入import json
  • 请添加有关错误的更多信息。目前尚不清楚异常在哪里,请使用tour,访问help center 并查看How to Ask
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多