Generate a JSON File with Pretty Formatted JSON Data in Python

Python has a built-in module called json that helps to serialize and deserialize JSON data. We can use this module to generate a JSON file with JSON pretty formatted data in Python.

Here is the complete example code to generate a JSON file with pretty formatted data in Python:


import json

json_data = [{"product_name":"abc", "id": 1, "price": 10.40},
             {"product_name":"def", "id": 1, "price": 15.45},
             {"product_name":"ghi", "id": 1, "price": 24.00},
             {"product_name":"klm", "id": 1, "price": 25.48}]

destination_filename_path = "D:\product_details.json"
print("generating json file started") 
with open(destination_filename_path, 'w') as file:
    json.dump(json_data, file, sort_keys=True, indent=4)

print("generating json file completed")    

The above code will generate a product.json file with the following pretty formatted data:

[
 {
  "id": 1,
  "price": 10.4,
  "product_name": "abc"
 },
 {
  "id": 1,
  "price": 15.45,
  "product_name": "def"
 },
 {
  "id": 1,
  "price": 24.0,
  "product_name": "ghi"
 },
 {
  "id": 1,
  "price": 25.48,
  "product_name": "klm"
 }
]