Home > Software engineering >  Not able to write to JSON files using python correctly
Not able to write to JSON files using python correctly

Time:01-29

So I have a discord bot which saved co-ordinates of some places in minecraft. But while saving the co-ordinates, I am not able to write to JSON file properly. It writes perfectly fine when i save the first time but when i run it again it gives me error.

Code:

@client.command(aliases = ["sc"])
async def save_cords(ctx, name,*, cords):
    uploader = ctx.author

    data = {"Uploader":f"{uploader}","Cords":f"{cords}","Name":f"{name}"}

    with open(f"test.json","a") as f:
        json.dump(data, f, indent=4)
        
    await ctx.send(f"Successfully saved cords. | Name: {name} | Cords: {cords}")

JSON file when written once:

{
    "Uploader": "SastaSushi#6366",
    "Cords": "-88 0 -110",
    "Name": "cords"
}

JSON file when written again:

{
    "Uploader": "SastaSushi#6366",
    "Cords": "-88 0 -110",
    "Name": "cords"
}{
    "Uploader": "SastaSushi#6366",
    "Cords": "-70 0 900",
    "Name": "village"
}

Here's the error when written the second time:

enter image description here

I want to make sure it writes in a manner where there is no error and I can read the data when wanted.

CodePudding user response:

So, the way u written is ultimately wrong the correct way is :

@client.command(aliases = ["sc"])
async def save_cords(ctx, name,*, cords):
    uploader = ctx.author
    with open("test.json",r) as file:
        data = json.load(file)
    nd = {}
    nd["uploader"] = uploader
    nd["Cords"] = cords
    nd["Name"] = name

    with open(f"test.json","a") as f:
        json.dump(nd, f, indent=4)
        
    await ctx.send(f"Successfully saved cords. | Name: {name} | Cords: {cords}")

Try This if it doesnt work reply me with error

CodePudding user response:

So, someone had posted an answer to this question but had deleted it, and it worked! So this is the code now:

@client.command(aliases = ["sc"])
async def save_cords(ctx, name, *, cords):
    uploader = ctx.author

    try:
        with open("Data\\file.json") as f:
            data = json.load(f)

    except FileNotFoundError:
        data = []

    if isinstance(data, dict):
        data = [data]

    data.append({"Uploader": f"{uploader}", "Cords": f"{cords}", "Name": f"{name}"})

    with open("Data\\file.json","w") as f:
        json.dump(data, f, indent=4)

    await ctx.send(f"Successfully saved cords. | Name: {name} | Cords: {cords}")```
  •  Tags:  
  • Related