Use JSON package and print method to print objects as JSON in Python. json.dumps() converts Python objects 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:
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 or suggestions on this Python JSON tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.