pythonjsondictionaryfile-manipulationpython-jsonschema

How should do you update JSON values of keys which are themselves values, with python


I have 2 files, one a test.json and the other my test.py My goal is to have the value of the key "test3" update and instead of being equal to a 3(like how it is shown below), update and turn into a 10.

Here is the test.json

 {
  "test": {
    "test2" : 3,
    "test3" : 5,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}

and here is the test.py

import json
with open('test.json','r') as t:
    data = json.load(t)

data["test3"] = 10

with open ('test.json','w') as t:
    json.dump(data,t)

After running, the output I expect to be is:

 {
  "test": {
    "test2" : 3,
    "test3" : 10,
    "test4" : [1,2,3]
  },
  "test5" : "hello"
}

Notice the "test3" value becomes a 10 but in reality, my output becomes:

{"test": {"test2": 3, "test3": 5, "test4": [1, 2, 3]}, "test5": "hello", "test3": 10}

The indentation is not the problem, rather its the fact that instead of changing "test3" from a 5 to a 10, it adds a new "test3" key with a value of 10 at the end and leaves the old one intact. I also have tried asking the program to just print out the values of any of the keys within "test" and it fails to do so and the only ones that work are either printing out the value of "test" itself or "test5" leading me to believe that their placement is what is messing it up. Any solutions to this would be appreciated and in case you are curious, I am unable to change the JSON files to be neater as a solution since I'm using this to work with the JSON files in the video game Minecraft and I fear messing with the pre-existing structure would interfere with how the game was designed to read its files.


Solution

  • You accessing the root of a nested doctionary, and there is no "test3" in there.. from your desired output i see that you should first access the inner dictionary stored under "test" and then change it ...

    
    import json
    with open('test.json','r') as t:
        data = json.load(t)
    
    data["test"]["test3"] = 10
    
    with open ('test.json','w') as t:
        json.dump(data,t)
    
    data
    >>>  {
      "test": {
        "test2" : 3,
        "test3" : 10,
        "test4" : [1,2,3]
      },
      "test5" : "hello"
    }