Python - 更改 JSON 值和漂亮的打印 [英] Python - change JSON values and pretty print

查看:40
本文介绍了Python - 更改 JSON 值和漂亮的打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在任何节点(value1、value2、value3、value4、value5、value6、value7)中使用 Python 更改 JSON 中的值:

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"
            }
        ]
    }
}

更改后例如Value6 和其他一些值 - 我想以漂亮的打印格式(与上面相同)打印新的 JSON.

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).

谢谢.

推荐答案

您需要先将字符串转换为 Python 字典,然后操作该字典,最后将字典转储回字符串.这是一个简单的例子:

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)

这篇关于Python - 更改 JSON 值和漂亮的打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆