1
votes

How to change Values in JSON by using Python in any of the nodes (value1, value2, value3, value4, value5, value6, value7):

{
    "key1": "value1",
    "level2": {
        "key2": "value2",
        "key3": "value3",
        "level3": [
            {
                "key4": "value4",
                "level5": [
                    {
                        "key5": "value5",
                        "key6": "value6"
                    }
                ],
                "key7": "value7"
            }
        ]
    }
}

After changing e.g. Value6 with some other value - I would like to print that new JSON in a nice print format (same as above).

Thanks.

1
Deserialize the json... modify the object, reserialize the json using the indent parameter to json.dump....juanpa.arrivillaga
what did you try¿Netwave
You call that format "nice"? Despite all that inconsistent spacing?Stefan Pochmann
Possible duplicate of How to update json file with pythonSimon

1 Answers

6
votes

You'll want to first convert the string to a python dictionary, then manipulate the dictionary, and finally dump the dictionary back to a string. Here's a simple example:

import json
json_string = '{"foo": "bar"}'
json_dict = json.loads(json_string)
json_dict["foo"] = "baz"
print json.dumps(json_dict, indent=4)