JSON Pretty Print Using Python- With Examples

May 25, 2018

2 mins read

Published in

JSON Pretty Print using Python is required frequently for testing, analyzing and debugging JSON data. Python and JSON both are treading in programming fields. Python generates dynamic JSON string and received by the client. To save memory or bandwidth it’s better to send the minified version of JSON text.

Some time for debugging purpose, we need to see beautified JSON data to understand and to Debug. This article will help to pretty print JSON data.

There are two examples in the post.

  1. Pretty Print JSON String
  2. Pretty Print JSON File

1. JSON Pretty Print using Python

Here is an Example:

1
2
3
4
5
6
7
8
import json

uglyjson = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'

#json.load method converts JSON string to Python Object
parsed = json.loads(uglyjson)

print json.dumps(parsed, indent=2, sort_keys=True)

Result :

1
2
3
4
5
6
7
8
{
  "firstnam": "James", 
  "mobile": [
    "007-700-007", 
    "001-007-007-0007"
  ], 
  "surname": "Bond"
}

Here is the explanation for the code.

  1. import json

This is a JSON library available in python to convert Python object from JSON string or from JSON file.

  1. json.load

json.load is a method which converts JSON string to Python object. Here is the conversion table form JSON data type to Python data types.

JSON Python
object dict
array list
string unicode
number (int) int,long
number (real) float
true True
false False
null None
  1. json.dumps

json.dums is the opposite of json.load. It creates a JSON string from Python object. It takes parameters indent parameter which formats the JSON string.

2. JSON Print Print from File using Python

Here is the Example:

1
2
3
4
5
6
import json

with open('jsonfile.txt') as jsonfile:
    parsed = json.load(jsonfile)

print json.dumps(parsed, indent=2, sort_keys=True)

This program reads from file and load and create Python objects and dumps the JSON data in beautiful JSON String. Read JSON File using Python for more details

I have used these tools for creating this blog post.

JSON Editor

JSON Viewer

 

Sharing is caring!