首页 > 编程语言 > 详细

python3 之 格式化json

时间:2018-11-24 11:10:57      阅读:170      评论:0      收藏:0      [点我收藏+]
import json

json_string = None

with open("json_file.json") as f:
    json_string = f.read()
try:
    parsed_json = json.loads(json_string)
    formatted_json = json.dumps(parsed_json, indent = 4,sort_keys=True)
    with open("json_file.json","w") as f:
        f.write(formatted_json)
except Exception as e:
    print(repr(e))

Parameter indent  decides the number of spaces to use for indentation.  

Parameter sort_keys decides whether the keys in formatted JSON should be in sorted order or not. Default value is False.    


Bonus: You can pretty-print the small JSON string directly at command terminal without using python script file. Use below line of code.

echo ‘{"first_name": "Anurag", "last_name": "rana"}‘ | python -m json.tool

python3 之 格式化json

原文:https://www.cnblogs.com/zxpo/p/10011078.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!