【问题标题】:Get name of JSON dictionary using automated python code使用自动化 python 代码获取 JSON 字典的名称
【发布时间】:2022-01-14 03:22:18
【问题描述】:

我的 Json 代码:

{
    "Axoland": {
        "id": "axoland",
        "president": 740107982842626078,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    },
    "NukeLand": {
        "id": "nukeland",
        "president": 583297391093088269,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    },
    "Greece": {
        "id": "greece",
        "president": 605355268854775828,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    },
    "Noname": {
        "id": "noname",
        "president": 594794892585205790,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    },
    "Gian Republic": {
        "id": "gian republic",
        "president": 749551090273615962,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    },
    "Tinspit": {
        "id": "tinspit",
        "president": 697865613057458276,
        "coPresident": [],
        "alliances": [],
        "unconfirmedAlliances": []
    }
}

Python 代码:

import json
def allc(ctx):
  f = open('saved.json', "r")
  data = json.loads(f.read())
  await ctx.send(data) #This is just sending the message in discord. Same output in print().

我正在为我和我的朋友制作一个不和谐机器人(请注意,您不需要 discord.py 方面的经验(我认为)来帮助我。只需 JSON 和 PYTHON 知识。)但它使用 json 数据。现在我有一个名为allc 的命令,它应该打印所有的名称(Axoland、NukeLand、Greece 等)。当我使用命令时,它返回的只是:

{'Axoland': {'id': 'axoland', 'president': 740107982842626078, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}, 'NukeLand': {'id': 'nukeland', 'president': 583297391093088269, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}, 'Greece': {'id': 'greece', 'president': 605355268854775828, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}, 'Noname': {'id': 'noname', 'president': 594794892585205790, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}, 'Gian Republic': {'id': 'gian republic', 'president': 749551090273615962, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}, 'Tinspit': {'id': 'tinspit', 'president': 697865613057458276, 'coPresident': [], 'alliances': [], 'unconfirmedAlliances': []}}

如何只获取名称而不获取数据?

【问题讨论】:

  • 我将 allc 更改为 def 而不是 async def 来提供帮助。它的输出 def 或 async def 相同。

标签: python json discord.py


【解决方案1】:

执行json.loads 操作后,此 JSON 将成为字典。

每个名字都是这本词典的一个键。

然后,要获取所有名称,请使用 sn-p 中的 data dict,只需执行 data.keys()

【讨论】:

  • 嗯。它成功了,但结果却是 dict_keys(['Axoland', 'NukeLand', 'Greece', 'Noname', 'Gian Republic', 'Tinspit'])。无论如何,足够好的信息,非常感谢!
  • 对不起,我的错。做列表(data.keys())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2021-08-31
  • 1970-01-01
  • 2016-08-07
  • 2011-06-21
  • 2020-09-14
  • 1970-01-01
相关资源
最近更新 更多