Python print object as JSON | Example code

Use JSON package and print method to print object as JSON in Python. json.dumps() converts Python object into a json string. Every object has an attribute that is denoted by dict and this stores the object’s attributes in Python.

Python example print object as json

Simple example code converts Python objects to JSON data.

import json

# Dict object:
obj = {
    "name": "John",
    "class": "First",
    "age": 5
}
print(type(obj))
# convert into JSON:
json_data = json.dumps(obj)

print(json_data)

Output:

Python print object as JSON

Another example

class Student object to JSON.

import json


# custom class
class Student:
    def __init__(self, roll_no, name, age):
        self.roll_no = roll_no
        self.name = name
        self.age = age


if __name__ == "__main__":
    # create two new student objects
    s1 = Student("101", "Tim", 16)
    s2 = Student("102", "Ken", 15)

    # convert to JSON format
    jsonstr1 = json.dumps(s1.__dict__)
    jsonstr2 = json.dumps(s2.__dict__)

    # print created JSON objects
    print(jsonstr1)
    print(jsonstr2)

Output:

{“roll_no”: “101”, “name”: “Tim”, “age”: 16}
{“roll_no”: “102”, “name”: “Ken”, “age”: 15}

Do comment if you have any doubts and suggestions on this Python JSON tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.