How do I convert a dictionary to a JSON object in Python?

Hi,

I have a project where we are getting the data from one source and the API used is returning the dictionary object.

Now our requirement is to convert it to JSON and save into Elasticsearch. We also have to save the json to a database in the JSON document.

I want to the easy way to convert the dictionary object to JSON data. I want to use any pre-built API.

Share me some of the examples.

Thanks

View Answers

July 17, 2021 at 6:16 PM

Hi,

In Python you are use the json library for this purpose.

Here is complete example:

import json  

#Sample dictionary

dict ={  
  "name": "Deepak Kumar",  
  "address": "India",  
  "age": 25,
  "education": "College"
}  

#Convert to the JSON object  
jsonObj = json.dumps(dict, indent = 4)  
print(jsonObj)

Above program will give following output:

>>> import json  
>>>        
... #Sample dictionary
... 
>>> dict ={  
...   "name": "Deepak Kumar",  
...   "address": "India",  
...   "age": 25,
...   "education": "College"
... }  
>>>        
... #Convert to the JSON object  
... jsonObj = json.dumps(dict, indent = 4)  
>>> print(jsonObj) 
{
    "name": "Deepak Kumar",
    "address": "India",
    "age": 25,
    "education": "College"
}

Hope this helps you.

Thanks


July 18, 2021 at 10:45 AM

Hi,

Here is the output of the program:

Python Tutorial

Thanks


July 18, 2021 at 10:47 AM

Hi,

Check many Python tutorials at:

Thanks









Related Tutorials/Questions & Answers:
Advertisements