Skip to content

Convert Python object to JSON | Example code

  • by

Use json.dumps() method to convert Python objects into a JSON string. You need to do is to pass the dictionary representation of the object as a parameter to this method.

json.dumps(Object obj)

Python object to JSON example

A simple example code of conversion of the class object to JSON is using JSON package in Python.

You have to import the JSON package into the program file.

import json

# object (dict):
dic_obj = {
    "name": "John",
    "class": "IV",
    "age": 10
}

print(type(dic_obj))

# Convert into JSON:
res = json.dumps(dic_obj)

print(res)

Output:

Convert Python object to JSON

Do comment if you have any doubts or suggestions on this Python Object and JSON topic.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *