【问题标题】:How can I get specific data from a json file - discord.py如何从 json 文件中获取特定数据 - discord.py
【发布时间】:2022-10-24 21:47:49
【问题描述】:

我需要从 json 文件中获取数据,但我不确定如何。 json文件的格式为:{"serverid": "data"}。如何获取当前的公会 ID,然后使用它从 json 文件中获取“数据”?顺便说一句,我正在使用 nextcord。

【问题讨论】:

  • 请提供更多信息和您编写的代码。然后我们可以查看您问题的特定部分。现在,这就像有人说“它不起作用”。那么,什么不起作用? “它”? “工作”具体是什么意思?
  • 您是否正在寻找有关如何使用 json 数据的教程?
  • @rv.kvetch 是的,这将非常有帮助。
  • @纯的。我会检查json 模块上的文档

标签: python discord discord.py nextcord


【解决方案1】:

你需要的是the json module

让我们以myjsonfile.json 为例,一个代表两个公会的 JSON 文件以及与它们关联的数据:

{"123456789012345678": "Some data", "876543210987654321": "Some other data"}

首先,你应该打开你的文件:

myjsonfile = open("myjsonfile.json")

然后,您可以将文件中的数据加载到字典中。您可以使用the json module 来做到这一点(不要忘记import json):

myjsondict = json.load(myjsonfile)

然后,您可以像往常一样使用 dict 访问数据:

# You should convert your guild ID to str, because JSON only accept string as a key
guild_id = str(123456789012345678)
print(myjsondict.get(guild_id))
print(myjsondict[guild_id])

# Output : "Some data"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-26
    • 2023-04-04
    • 2021-12-04
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多