【问题标题】:Storing dictionaries in json file将字典存储在 json 文件中
【发布时间】:2022-01-07 09:57:53
【问题描述】:

我正在尝试将字典存储在用户输入的 JSON 文件中。代码是:

@client.command()
async def shibaku0(ctx, coin1, coin2, coin3, coin4, coin5, coin6, shibakunumber, oslink):
  
    
    await ctx.message.delete()
    
    with open('Shibaku0.json', 'r') as f:
      coins_data = json.load(f)
    coins_data[str(ctx.author.id)]["coins"] = (coin1, coin2, coin3, coin4, coin5, coin6)
    shibakunumber[str(ctx.author.id)]["shibakunumber"] = (shibakunumber)
    oslink[str(ctx.author.id)]["oslink"] = (oslink)
    
    with open('Shibaku0.json', 'w') as f:
      json.dump(coins_data, f)
    

    embed=discord.Embed(title="Shibaku0", url=f'{oslink}', description=f'No. {shibakunumber}')
    embed.add_field(name="Coins: ", value=f'{coin1} {coin2} {coin3} {coin4} {coin5} {coin6}', inline=True)
    embed.set_footer(text=f"{ctx.author.name}'s Shibaku")
    await ctx.send(embed=embed)

我想存储“coins”、“shibakunumber”、“oslink”,但是当我尝试运行代码时收到此错误消息:

TypeError: 列表索引必须是整数或切片,而不是 str

【问题讨论】:

  • 一个有效的 JSON 文件通常以 {[ 开头。在{ 的情况下,这是一个类似于python 中的dict 的对象。以[开头表示它是一个类似python中list的数组。
  • 那么我需要更改哪个支架才能使其工作? @MYousefi
  • 您的数据应该是什么样的?它是单个实体还是实体列表,每个实体都有自己的 id 和硬币?
  • 基本上我想看起来像:" userid: { coin: "value", shibakunumber: "value" oslink: "link format" " 这是因为我希望能够单独调用每个项目@MYousefi

标签: discord.py


【解决方案1】:

制作一个关联数组(JSON 对象/字典)的 json。您需要在文件中有{ 或单个对象。每个对象将userid 与该用户的数据相关联,即嵌套对象。

这是一个示例:

import json
# sample_data/Obj.json
# {
#   "user1": {"coins":  "coinstringvalue", "shibakunumber": 1, "oslink": "linkstringvalue"},
#   "user2": {"coins":  "coinstringvalue2", "shibakunumber": 2, "oslink": "linkstringvalue2"}
# }
mydata = json.load(open('sample_data/Obj.json', 'r'))
print(mydata['user1'])
print(mydata['user2'])
print(mydata['user2']['shibakunumber'])

这给出了输出:

{'coins': 'coinstringvalue', 'shibakunumber': 1, 'oslink': 'linkstringvalue'}
{'coins': 'coinstringvalue2', 'shibakunumber': 2, 'oslink': 'linkstringvalue2'}
2

请注意,mydata 在 python 中是 dict 类型。

这是一个从空 json 文件开始的示例。

import json
# sample_data/empty.json
# {}

mydata = json.load(open('sample_data/empty.json', 'r'))
print(mydata)
# author_id = str(ctx.author.id)
author_id = str(1161214)
if author_id not in mydata:
  mydata[author_id] = dict()
mydata[author_id]['coins'] = ("coin1", "coin2")
mydata[author_id]['shibakunumber'] = 2
mydata[author_id]['oslink'] = "somelink"

json.dump(mydata, open('sample_data/new_file.json', 'w'))
loaded_data = json.load(open('sample_data/new_file.json', 'r'))

print(loaded_data)

生产:

mydata {}
loaded_data {'1161214': {'coins': ['coin1', 'coin2'], 'shibakunumber': 2, 'oslink': 'somelink'}}

【讨论】:

  • 这不起作用吗?
  • 你的'Shibaku0.json'的内容是什么?
  • @MYouseif 我将如何调用并仅打印“oslink”,我有此代码@client.command(aliases = ["shib, shibaku, Shib"]) async def Shibaku(ctx, int = 0): if int == 0: with open('Shibaku0.json') as f: coins_data = json.load(f) for oslink in coins_data[str(ctx.author.id)]["oslink"]: await ctx.send(oslink) 但它逐个发送链接而不是整个内容
  • 我将它声明为变量并打印出来oslink = users[str(ctx.author.id)]["oslink"] await ctx.send(oslink)
  • 你在那里做的是循环 oslink 值。只需发送coins_data[str(ctx.author.id)]["oslink"] 并删除for oslin in ...
猜你喜欢
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多