1

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.

Joe
  • 11,983
  • 31
  • 109
  • 183

1 Answers1

6

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)
Pwnosaurus
  • 2,058
  • 1
  • 19
  • 21
  • 1
    This works good and just wondering is there a way to keep order of KEYS the same as in original string? For example - sometimes I get KEY7 before KEY4 (but in correct level) when convert to dictionary and then print out with json.dumps.... – Joe Jan 17 '18 at 19:44
  • 2
    It's a bit more complicated, but check out this answer: https://stackoverflow.com/a/6921760/1739725 – Pwnosaurus Jan 17 '18 at 19:45