首页 > 解决方案 > 无法将 json 转储变量转换到单独的行

问题描述

我正在尝试将 json 转储打印到多行。目前它在一行上打印。

这是我正在尝试的步骤;

第 1 步:这是我要打印的代码

payload = json.dumps({"ip-detunnel": "No",
                      "name": "DP800 Slot 1",
                      "vlan-tag-insertion": "No",
                      "vlan-tag-remove-forward": "Remove",
                      "mac-replace-header": "No",
                      "mpls-label-stack": "Pass Through"
                      })

第2步:这就是我尝试打印的方式

print '\n' + payload

第 3 步:结果如下:

{"vlan-tag-insertion": "No", "name": "DP800 Slot 1", "mpls-label-stack": "Pass Through", "vlan-tag-remove-forward": "Remove", "ip-detunnel": "No", "mac-replace-header": "No"}

我的目标是在多行上打印结果,使其看起来像步骤 1 中的 json.dumps

标签: pythonjson

解决方案


传给indent=4_dumps

payload = json.dumps({"ip-detunnel": "No", "name": "DP800 Slot 1", "vlan-tag-insertion": "No", "vlan-tag-remove-forward": "Remove", "mac-replace-header": "No", "mpls-label-stack": "Pass Through" }, indent=4)

或除 0 以外的任何其他数字。 json 对象的每个嵌套都将缩进它之前的那么多空格。输出:

>>>print(payload)
{
    "ip-detunnel": "No",
    "name": "DP800 Slot 1",
    "vlan-tag-insertion": "No",
    "vlan-tag-remove-forward": "Remove",
    "mac-replace-header": "No",
    "mpls-label-stack": "Pass Through"
}


推荐阅读