Open In App

How to return a json object from a Python function?

Last Updated : 20 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to get its equivalent JSON object.

Approach:

  • Import module
  • Create a Function
  • Create a Dictionary
  • Convert Dictionary to JSON Object Using dumps() method
  • Return JSON Object

Syntax: json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Implementation using the above approach is given below:

Example 1:

Python3




# Import Module
import json
 
# Create geeks function
 
 
def geeks():
 
    # Define Variable
    language = "Python"
    company = "GeeksForGeeks"
    Itemid = 1
    price = 0.00
 
    # Create Dictionary
    value = {
        "language": language,
        "company": company,
        "Itemid": Itemid,
        "price": price
    }
 
    # Dictionary to JSON Object using dumps() method
    # Return JSON Object
    return json.dumps(value)
 
 
# Call Function and Print it.
print(geeks())


Output:

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

Example 2: Using the list as Dictionary value.

Python3




# Import Module
import json
 
# Create geeks function
 
 
def geeks():
 
    # Create Dictionary
    value = {
        "firstName": "Pawan",
        "lastName": "Gupta",
        "hobbies": ["playing", "problem solving", "coding"],
        "age": 20,
        "children": [
            {
                "firstName": "mohan",
                "lastName": "bansal",
                "age": 15
            },
            {
                "firstName": "prerna",
                "lastName": "Doe",
                "age": 18
            }
        ]
    }
 
    # Dictionary to JSON Object using dumps() method
    # Return JSON Object
    return json.dumps(value)
 
 
# Call Function and Print it.
print(geeks())


Output:

{“firstName”: “Pawan”, “lastName”: “Gupta”, “hobbies”: [“playing”, “problem solving”, “coding”], “age”: 20, “children”: [{“firstName”: “mohan”, “lastName”: “bansal”, “age”: 15}, {“firstName”: “prerna”, “lastName”: “Doe”, “age”: 18}]}



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads