Categories
Python Answers

How to pretty print a JSON file with Python?

Spread the love

Sometimes, we want to pretty print a JSON file with Python.

In this article, we’ll look at how to pretty print a JSON file with Python.

How to pretty print a JSON file with Python?

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

For instance, we write:

import json

your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=2, sort_keys=True))

We call json.loads with your_json to load the JSON string into a dictionary.

Then we call json_dumps with the parsed JSON and indent set to 2 to indent each level with 2 spaces.

sort_keys is set to True to sort the keys alphabetically.

Therefore,

[
  "foo",
  {
    "bar": [
      "baz",
      null,
      1.0,
      2
    ]
  }
]

is printed.

Conclusion

To pretty print a JSON file with Python, we can use the json.dumps method with the indent and sort_keys parameters.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *