麻烦将json转储变量放到单独的行中

时间:2019-05-05 14:24:56

标签: python 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

1 个答案:

答案 0 :(得分:2)

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