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

相关文章:

  • 2021-09-15
  • 2021-09-06
  • 2021-08-22
  • 2021-06-20
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-14
  • 2021-07-26
  • 2021-08-05
  • 2021-09-24
  • 2021-09-17
相关资源
相似解决方案