"+=" operator not working when modifying .json in variable (Python)

  json, python

I’m new to Python, and I’m trying to store data in a .json, and then access and modify it through Python. Currently I’m having an issue where I can’t modify the data if I try to use a variable instead of directly modifying it. It works fine if it’s not in a variable, or if I’m just reading the information, or if it’s not in a function.

import json

with open('testprog.json', 'r+') as f:
    data = json.load(f)
    x = int(data['valueOne'])
    def test():
        x += 1
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

    test()
    print("New first value is: "+str(data['valueOne']))

.json:

{
    "valueOne": 10,
    "valueTwo": 5,
    "valueThree": 8
}

Source: Python Questions

LEAVE A COMMENT