您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页python3 之 格式化json

python3 之 格式化json

来源:伴沃教育
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

转载于:https://www.cnblogs.com/zxpo/p/10011078.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务