JSON Pretty Print using Python - GeeksforGeeks

08 Dec, 2020
JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages. It is commonly used for data transmission between client-server applications. Usually, minified versions of JSON text are transmitted to save bandwidth. However, for debugging and analysis, a beautified version or a pretty print of JSON is required. Essentially, pretty printing JSON means having proper indentation, white spaces and separators. This article explores how to pretty print JSON using Python.  
Python has a built-in module called json that allows working with JSON data and how it can be used for out functionality is given in the following steps:
Import the JSON package.
Then depending on the scenario-
Reading from a JSON file and pretty printing it,Writing pretty printed JSON to a file, orsimply pretty printing JSON string data.
Reading from a JSON file and pretty printing it,
Writing pretty printed JSON to a file, or
simply pretty printing JSON string data.
Below are examples and steps to better understand these cases.
First, use json.loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json.dumps() method is used. 
Syntax:
json.dumps(indent,separator)
This method has the parameter indent to specify the number of spaces and a separator parameter to specify the separator between key and value. By default, the separator is a comma between key-value pairs, and a colon between key and value. If the indent parameter of json.dumps() is negative, 0 or an empty string then there are no indentations and only newlines are inserted. By default, indent is None and the data is represented in a single line.
Example:
Python3
# Import required librariesimport json  # Initialize JSON datajson_data = '[ {"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]}, \                {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]} ]'  # Create Python object from JSON string dataobj = json.loads(json_data)  # Pretty Print JSONjson_formatted_str = json.dumps(obj, indent=4)print(json_formatted_str)
Output:
[
   {
       "studentid": 1,
       "name": "ABC",
       "subjects": [
           "Python",
           "Data Structures"
       ]
   },
   {
       "studentid": 2,
       "name": "PQR",
       "subjects": [
           "Java",
           "Operating System"
       ]
   }
]
To write a Python object as JSON formatted data into a file, json.dump() method is used. Like json.dumps() method, it has the indents and separator parameters to write beautified JSON.
Example:
Python3
# Import required librariesimport json  data = [{"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]},        {"studentid": 2, "name": "PQR", "subjects": ["Java", "Operating System"]}]  # Write pretty print JSON data to filewith open("filename.json", "w") as write_file:    json.dump(data, write_file, indent=4)
Output:
filename.json
To read JSON from a file or URL, use json.load(). Then use json.dumps() to convert the object (obtained from reading the file) into a pretty print JSON string. 
Example:
Python3
# Import required librariesimport json  # Read JSON data from file and pretty print itwith open("filename.json", "r") as read_file:    # Convert JSON file to Python Types    obj = json.load(read_file)      # Pretty print JSON data    pretty_json = json.dumps(obj, indent=4)    print(pretty_json)
Output:
[
   {
       "studentid": 1,
       "name": "ABC",
       "subjects": [
           "Python",
           "Data Structures"
       ]
   },
   {
       "studentid": 2,
       "name": "PQR",
       "subjects": [
           "Java",
           "Operating System"
       ]
   }
]
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()