【问题标题】:How to pretty print json String whose value is also a json String in python如何漂亮地打印json字符串,其值也是python中的json字符串
【发布时间】:2020-11-19 15:34:08
【问题描述】:

我正在使用 python 的 json 模块来漂亮地打印一个如下所示的 json 字符串

"{"content" : "{"key" : "value"}","otherContent: "{"key2":"value"}"}"

我希望它在打印时看起来像这样

{ 
 c1: {
       key: value
     },
 c2: {
        key2: value
     }
}

或类似这种格式的东西,我怎样才能做到这一点?

【问题讨论】:

  • 这是最大深度吗(即内部 JSON 字符串中是否可以包含另一个 JSON 字符串)?
  • 把那个 json 变成 dict,然后 pprint(dict) - 参考:看 pprint docs.python.org/3/library/pprint.html
  • 这能回答你的问题吗? How to prettyprint a JSON file?
  • “一个 json 字符串”是什么意思?一旦你有了一个字符串,它就是一个字符串,不管你是通过加载json文档还是其他方式得到的。
  • 将 json 转为 dict,然后 pprint(dict) !这工作谢谢!

标签: python json pretty-print


【解决方案1】:

我不得不通过添加一些方括号来重新格式化您的 json,但这有效:

json_string = '{"content": [{"key": "value"}], "otherContent": [{"key2": "value"}]}'

loaded_json = json.loads( json_string )

print(json.dumps(loaded_json , sort_keys=True, indent=4))

输出:

{
    "content": [
        {
            "key": "value"
        }
    ],
    "otherContent": [
        {
            "key2": "value"
        }
    ]
}

【讨论】:

    猜你喜欢
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多