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.
- Pretty Print JSON String
- Pretty Print JSON File
1. JSON Pretty Print using Python
Here is an Example:
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 :
{ "firstnam": "James", "mobile": [ "007-700-007", "001-007-007-0007" ], "surname": "Bond" }
Here is the explanation for the code.
import json
This is a JSON library available in python to convert Python object from JSON string or from JSON file.
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 |
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:
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.