JSON prettify in Python
Using the native json
Python module, JSON data can be pretty-printed.
Pretty print JSON string in Python
1import json
2data = '{"users": [{"id":1,"name":"Thomas"},{"id":2,"name":"Sally"}]}'
3obj = json.loads(data)
4print(json.dumps(obj, indent=2))
Output:
1{
2 "users": [
3 {
4 "id": 1,
5 "name": "Thomas"
6 },
7 {
8 "id": 2,
9 "name": "Sally"
10 }
11 ]
12}
- The
json.loads()
method creates a Python dictionary from a givenjson
string. - The
json.dumps()
method outputs ajson
string from a given Python dictionary. In addition, theindent
parameter defines the level of the indent in the resulting string.
Pretty print JSON file data in Python
1import json
2
3with open("users.json", "r") as json_file:
4 obj = json.load(json_file)
5
6print(json.dumps(obj, indent=2))
Output:
1{
2 "users": [
3 {
4 "id": 1,
5 "name": "Thomas"
6 },
7 {
8 "id": 2,
9 "name": "Sally"
10 }
11 ]
12}
- The
json.load()
method creates a Python dictionary from a given file. - The
json.dumps()
method outputs ajson
string from a given Python dictionary. In addition, theindent
parameter defines the level of the indent in the resulting string.