I'm trying a deduct a value in json but since it take away a digit a problem occurs

Question:

Sounds easy but I’ve been trying to find a fix for this problem but I would like to know if there is any fix at all.

with open('py.json','r+',encoding='utf-8') as f:
    data = json.load(f)
    f.seek(0)
    data['numbers'][0]['value'] = data['numbers'][0]['value']-1
    json.dump(data, f, indent=4)

Before:

{
    "numbers": [
        {
            "value": 10
        }
    ]
}

A simple way of adding or (in this case) subtracting an int as a value. The value starts off as 10. This is what happens after the code is ran.

After:

{
    "numbers": [
        {
            "value": 9
        }
    ]
}}

An extra "}" is placed at the end of the file, seemingly filling in for the missing digit for the number 10. The weird thing is that if I print "data", all curly brackets are closed. How can I get rid of that one extra bracket?

Asked By: deezee

||

Answers:

Call f.truncate() after writing to clear old content that remains after the end of the new written content

with open('py.json','r+',encoding='utf-8') as f:
    data = json.load(f)
    f.seek(0)
    data['numbers'][0]['value'] = data['numbers'][0]['value']-1
    json.dump(data, f, indent=4)
    f.truncate()
Answered By: Iain Shelvington
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.