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 json
def geeks():
language = "Python"
company = "GeeksForGeeks"
Itemid = 1
price = 0.00
value = {
"language" : language,
"company" : company,
"Itemid" : Itemid,
"price" : price
}
return json.dumps(value)
print (geeks())
|
Output:
{“language”: “Python”, “company”: “GeeksForGeeks”, “Itemid”: 1, “price”: 0.0}
Example 2: Using the list as Dictionary value.
Python3
import json
def geeks():
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
}
]
}
return json.dumps(value)
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}]}