python3 之 格式化json
Posted zxpo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于python3 之 格式化json的主要内容,如果未能解决你的问题,请参考以下文章