gim
gim

Reputation: 99

Storing dictionaries in json file

I am trying to store dictionaries in a JSON file which user input. The code is:

@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)

I want to store the "coins", "shibakunumber, "oslink", but I am getting this error message when I try and run the code:

TypeError: list indices must be integers or slices, not str

Upvotes: 0

Views: 86

Answers (1)

MYousefi
MYousefi

Reputation: 1008

To make a json that is an associative array (JSON object / dict). You need to have { or a single object within the file. Each object associates userid with the data for that user, i.e, a nested object.

Here's a sample :

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'])

This gives the output:

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

Note that the mydata is a dict type in python.

Here's an example of starting with an empty json file.

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)

Produces:

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

Upvotes: 1

Related Questions