Python - change JSON values and pretty print

烈酒焚心 提交于 2020-05-16 03:16:55

问题


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:


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)


来源:https://stackoverflow.com/questions/48308356/python-change-json-values-and-pretty-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!