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 Lazyroar function def Lazyroar(): # 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 (Lazyroar()) |
Output:
{“language”: “Python”, “company”: “GeeksForGeeks”, “Itemid”: 1, “price”: 0.0}
Example 2: Using the list as Dictionary value.
Python3
# Import Module import json # Create Lazyroar function def Lazyroar(): # 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 (Lazyroar()) |
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}]}