Pretty Print JSON in Python
Last Updated :
26 Feb, 2023
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:
Python3
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)
print (json.dumps(json_object, indent = 1 ))
print (json.dumps(json_object, indent = 3 ))
|
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"
}
]
Time complexity: O(1)
Auxiliary space: O(1)
Example 2: Let’s suppose we want to pretty-print the data from the JSON file. JSON File:
Python3
import json
f = open ( 'myfile.json' ,)
data = json.load(f)
print (json.dumps(data, indent = 1 )
f.close()
|
Output:
{
"emp1": {
"name": "Lisa",
"designation": "programmer",
"age": "34",
"salary": "54000"
},
"emp2": {
"name": "Elis",
"designation": "Trainee",
"age": "24",
"salary": "40000"
}
}
Share your thoughts in the comments
Please Login to comment...