Skip to content
Related Articles

Related Articles

How to return a json object from a Python function?
  • Last Updated : 13 Jan, 2021

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 covert 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}]}

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :