Open In App

How to return a json object from a Python function?

Last Updated : 28 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Returning a JSON object from a Python function involves converting Python data (like dictionaries or lists) into a JSON-formatted string or response, depending on the use case. For example, if you're working with APIs, you might return a JSON response using frameworks like Flask. Let's explore several efficient methods to return a JSON object from a Python function.

Using json.dumps()

This is the most basic and widely-used way to convert a Python dictionary to a JSON string using Python’s built-in json module. It doesn't require any third-party packages or frameworks.

Python
import json
def fun():
    d = {
        "language": "Python",
        "company": "GeeksForGeeks",
        "Itemid": 1,
        "price": 0.00
    }
    return json.dumps(d)
print(fun())

Output
{"language": "Python", "company": "GeeksForGeeks", "Itemid": 1, "price": 0.0}

Explanation: fun() function creates a dictionary with details like language, company, item ID and price, then uses json.dumps() to convert it into a JSON string. print(fun()) calls the function and prints the JSON output to the console.

Using orjson

orjson is a high-performance JSON library for Python. It is faster and more efficient than the standard json module, especially when working with large data or requiring faster serialization.

Python
import orjson
def fun():
    d = {
        "language": "Python",
        "company": "GeeksForGeeks",
        "Itemid": 1,
        "price": 0.00
    }
    return orjson.dumps(d).decode()
print(fun())

Output

{"language":"Python","company":"GeeksForGeeks","Itemid":1,"price":0.0}

Explanation: fun() function creates a dictionary with details like language, company, item ID and price, then uses orjson.dumps() to convert it into a JSON string. Since orjson returns bytes, .decode() is used to convert it to a string.

Using jsonify()

jsonify() is part of Flask and is used to create a proper HTTP JSON response. It is the best choice when you're building a web API or returning JSON data from a Flask route.

Python
from flask import Flask, jsonify
app = Flask(__name__)

def fun():
    d = {"language": "Python"}
    return jsonify(d)

with app.app_context():
    response = fun()
    print(response.get_data(as_text=True))

Output

{"language":"Python"}

Explanation: fun() function creates a dictionary and uses jsonify() to convert it into a JSON response. Since jsonify() requires a Flask context, app.app_context() is used. The response is then printed using response.get_data(as_text=True).


Next Article
Article Tags :
Practice Tags :

Similar Reads