最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中如何输出格式化带缩进的JSON字符串

JSON crifan 4044浏览 0评论

想要把json字典对象,格式化打印出来。

python print pretty json

参考:

python – How to prettyprint a JSON file? – Stack Overflow

7.12. pprint — Data pretty printer — Python v3.2.6 documentation

18.2. json — JSON encoder and decoder — Python 2.7.14 documentation

Pretty Printing a Python dictionary (Example)

用代码:

<code>def jsonToPrettyStr(jsonDict, indent=4):
</code>

效果:

<code>Current config: {u'msStore': {u'productList': [{u'productNameToSearch': u'Dell Inspiron 15 i7559-5012GRY Signature Edition Laptop', u'expectPrice': 1099, u'productUrl': u'', u'buyNum': 2}], u'homeUrl': u'https://www.microsoft.com/en-us/store/b/home';}, u'outputFolder': u'output', u'isResetOutput': True, u'needScreenshot': False, u'waitTimeout': 10}
</code>

和:

<code>Current config:
{
    "msStore": {
        "productList": [
            {
                "productNameToSearch": "Dell Inspiron 15 i7559-5012GRY Signature Edition Laptop", 
                "expectPrice": 1099, 
                "productUrl": "", 
                "buyNum": 2
            }
        ], 
        "homeUrl": "https://www.microsoft.com/en-us/store/b/home";
    }, 
    "outputFolder": "output", 
    "isResetOutput": true, 
    "needScreenshot": false, 
    "waitTimeout": 10
}
</code>

另外再去试试pprint

<code>import pprint
</code>

但是才发现:

此处Python 是2.x没有pprint,只有Python 3.x才有pprint

所以算了。抽空再去优化。

【总结】

最终优化为:

支持输入json的字典对象或者本身就是json字符串,格式化输出为带缩进的json字符串。

完整代码详见:

https://github.com/crifan/crifanLib/blob/master/python/crifanLib.py

或:

https://github.com/crifan/crifanLib/blob/master/python/crifanLib/crifanString.py

转载请注明:在路上 » 【已解决】Python中如何输出格式化带缩进的JSON字符串

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.166 seconds, using 22.05MB memory