Print an object as JSON in Python

avatar

Borislav Hadzhiev

Last updated: Sep 8, 2022

banner

Photo from Unsplash

Print an object as JSON in Python #

Use the json.dumps() method to print an object as JSON, e.g. print(json.dumps(my_dict)). The json.dumps() method converts a Python object to a JSON formatted string.

main.py
import json my_dict = {'id': 1, 'name': 'BobbyHadz'} # ✅ Print object as JSON json_str = json.dumps(my_dict) print(json_str) # 👉️ {"id": 1, "name": "BobbyHadz"} # ------------------------------------------------- # ✅ Pretty print object as JSON json_str = json.dumps(my_dict, indent=4) # { # "id": 1, # "name": "BobbyHadz" # } print(json_str) # ------------------------------------------------- # ✅ Print class instance as JSON class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary bobby = Employee('bobby', 100) json_str = json.dumps(bobby.__dict__) print(json_str) # 👉️ {"name": "bobby", "salary": 100}

We used the json.dumps() method to print an object as JSON.

The json.dumps method converts a Python object to a JSON formatted string.

main.py
import json my_dict = {'id': 1, 'name': 'BobbyHadz'} json_str = json.dumps(my_dict) print(json_str) # 👉️ {"id": 1, "name": "BobbyHadz"} print(type(json_str)) # 👉️ <class 'str'>

If you have a JSON string and need to convert it to a native Python object, use the json.loads() method.

main.py
import json my_dict = {'id': 1, 'name': 'BobbyHadz'} json_str = json.dumps(my_dict) print(json_str) # 👉️ {"id": 1, "name": "BobbyHadz"} native_obj = json.loads(json_str) print(native_obj) # 👉️ {'id': 1, 'name': 'BobbyHadz'}

The json.loads method parses a JSON string into a native Python object.

If you need to pretty print an object as JSON, set the indent argument to 4 in the call to json.dumps().

main.py
import json my_dict = {'id': 1, 'name': 'BobbyHadz'} json_str = json.dumps(my_dict, indent=4) # { # "id": 1, # "name": "BobbyHadz" # } print(json_str)

If indent is set to a non-negative integer, the JSON array elements or object members get pretty-printed with the specified indent level.

Print a class object as JSON in Python #

To print a class object as JSON:

  1. Access the __dict__ attribute on the class instance.
  2. Pass the result to the json.dumps() method.
  3. Use the print() function to print the JSON representation of the object.
main.py
import json class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary bobby = Employee('bobby', 100) json_str = json.dumps(bobby.__dict__) print(json_str) # 👉️ {"name": "bobby", "salary": 100}
The default JSONEncoder class can't directly convert class instances to JSON, so we had to use the __dict__ attribute on the instance.

The __dict__ attribute returns a dictionary that contains the attributes of the instance and can be passed to the json.dumps() method.

main.py
import json class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary bobby = Employee('bobby', 100) print(bobby.__dict__) # 👉️ {'name': 'bobby', 'salary': 100} json_str = json.dumps(bobby.__dict__) print(json_str) # 👉️ {"name": "bobby", "salary": 100}

The JSONEncoder class supports the following objects and types by default.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

Notice that the JSONEncoder class doesn't support class instance to JSON conversion by default.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.