Pretty Print JSON in Python

JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json.

Note: For more information, refer to Read, Write and Parse JSON using Python

Pretty Print JSON

Whenever data is dumped into Dictionary using the inbuilt module “json” present in Python, the result displayed is same as the dictionary format. Here the concept of Pretty Print Json comes into picture where we can display the JSON loaded into a presentable format.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Write Python3 code here
   
import json
   
json_data = '[{"Employee ID":1,"Name":"Abhishek","Designation":"Software Engineer"},' \
            '{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'
   
json_object = json.loads(json_data)
   
# Indent keyword while dumping the
# data decides to what level 
# spaces the user wants.
print(json.dumps(json_object, indent = 1))
   
# Difference in the spaces 
# near the brackets can be seen
print(json.dumps(json_object, indent = 3))

chevron_right


Output:



[
 {
  "Employee ID": 1,
  "Name": "Abhishek",
  "Designation": "Software Engineer"
 },
 {
  "Employee ID": 2,
  "Name": "Garima",
  "Designation": "Email Marketing Specialist"
 }
]
[
   {
      "Employee ID": 1,
      "Name": "Abhishek",
      "Designation": "Software Engineer"
   },
   {
      "Employee ID": 2,
      "Name": "Garima",
      "Designation": "Email Marketing Specialist"
   }
]

Example 2: Let’s suppose we want to pretty-print the data from the JSON file.

JSON File:

pretty-print-json

filter_none

edit
close

play_arrow

link
brightness_4
code

import json 
     
# Opening JSON file 
f = open('myfile.json',) 
     
# returns JSON object as  
# a dictionary 
data = json.load(f) 
     
print(json.dumps(data, indent = 1)
     
# Closing file 
f.close() 

chevron_right


Output:

{
 "emp1": {
  "name": "Lisa",
  "designation": "programmer",
  "age": "34",
  "salary": "54000"
 },
 "emp2": {
  "name": "Elis",
  "designation": "Trainee",
  "age": "24",
  "salary": "40000"
 }
}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.