How to format JSON with python

We can format minified json with python. Python has built in JSON module. We will add indentation in the minified json to format it.

First example format JSON add space


import json


minified_json_example = '{"text":"Hi There","type":"greeting","word":"2"}'

#convert it to python dictonary
python_dictionarty = json.loads(minified_json_example)


#We will use 4 space indentation to format and convert it to json again
formatted_json = json.dumps(python_dictionarty, indent=4)

print(formatted_json)


It will show the result like this

{
    "text": "Hi There",
    "type": "greeting",
    "word": "2"
}

Open a JSON file and format it


import json

filename = 'example.json'

formatted_json = json.dumps(json.load(open(filename, 'r')), indent=4)

print(formatted_json)


#Save formatted JSON to a new file
new_filename = 'formatted_example.json'
with open(new_filename, 'w') as f:
    json.dump(json.loads(formatted_json), f, indent=4)


You can also minify json with python


import json


python_dictionary = {
    "text": "Hi There",
    "type": "greeting",
    "word": "2"
}

formatted_json = json.dumps(python_dictionary, indent=4)
print(formatted_json)

#remove whitespace and indentation
minified_json = json.dumps(python_dictionary, separators=(',', ':'))
print(minified_json)