how.wtf

JSON prettify in Python

· Thomas Taylor

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}
  1. The json.loads() method creates a Python dictionary from a given json string.
  2. The json.dumps() method outputs a json string from a given Python dictionary. In addition, the indent 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}
  1. The json.load() method creates a Python dictionary from a given file.
  2. The json.dumps() method outputs a json string from a given Python dictionary. In addition, the indent parameter defines the level of the indent in the resulting string.

#python  

Reply to this post by email ↪