2

Update: The only issue I have now is when running the command to add a user it create a completely duplicate key.

Question: json.dump() simply adds the entry to the end of the json, I want it to overwrite the entire file with the new updated entry

Setup: (Create blank "Banks" Field)

        with open(DATA_FILENAME, mode='w', encoding='utf-8') as f:
            data = {"banks": []}
            json.dump(data, f)

Set User: (Create a User Key inside "Banks")

            member = ctx.message.author
            entry = {'name': member.name, 'id': member.id, 'balance': 0}

            with open(DATA_FILENAME, 'r+') as outfile:
                data = json.load(outfile)
                data['banks'].append((entry))
                json.dump(data, outfile, indent=4)

Output of first use:

{"banks": []}{
    "banks": [
        {
            "name": "ViperZ-14",
            "id": 367151547575959562,
            "balance": 0
        }
    ]
}

What I need:

{
    "banks": [
        {
            "name": "ViperZ-14",
            "id": 367151547575959562,
            "balance": 0
        }
    ]
}
Jamie
  • 101
  • 1
  • 10

2 Answers2

1
file_path = '/home/vishnudev/Downloads/new.json'
import json

def load(file, mode, data=[]):
    with open(file, mode) as f:
        if mode == 'r':
            return json.load(f)
        elif mode == 'w':
            json.dump(data, f)

def get_data_func():
    return {
        'name': 'vishnu',
        'data': 'dev'
    }

d = load(file_path, 'r')
print(d)

d.append(get_data_func())

load(file_path, 'w', d)

d = load(file_path, 'r')
print(d)

Output:

On running the above twice I get

[{'name': 'vishnu', 'data': 'dev'}]
[{'name': 'vishnu', 'data': 'dev'}, {'name': 'vishnu', 'data': 'dev'}]
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

I have found that the solution was to simply seek to the beginning of the document. The json.dump() does overwrite but it only overwrites whats in its way. AKA, seeking/placing the cursor at the top of the document will overwrite the entire document using the new entry.

Jamie
  • 101
  • 1
  • 10