skip to Main Content

I am trying to read a json file, modify and then save the modified version.
Unfortunately, the content of the file, instead of being saved, adds another json to the end of the original one.

my code:

with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
    test = json.load(test_file)
    test['COMPONENTS'] = "test components"
    json.dump(test, test_file)

test.json
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}

after running code
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}

expected result:
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}

Please point out what I am doing wrong

My environment
Python 3.10.9
macos 12.3.1

I try to use w+

Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0

During handling of the above exception, another exception occurred:

  File "/test.py", line 20, in <module>
    test = json.load(test_file)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

2

Answers


  1. I think the problem is adding a + to your opening modes. Also note that w+ would truncate the file, so there will be no JSON to read. I think what you should do is:

    with open(os.environ.get("WORKSPACE")+"/test.json", 'r') as test_file:
        test = json.load(test_file)
        test['COMPONENTS'] = "test components"
    
    with open(os.environ.get("WORKSPACE")+"/test.json", 'w') as test_file:
        json.dump(test, test_file)
    
    Login or Signup to reply.
  2. The easiest way to do it, like UpmostScarab said, is to just open the file twice. If you only want to open it once for some reason, you can read, then seek(0), then write, and finally truncate:

    with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
        test = json.load(test_file)
        test['COMPONENTS'] = "test components"
        test_file.seek(0)
        json.dump(test, test_file)
        test_file.truncate()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search