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

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

Ads









Related Tutorials/Questions & Answers:
How do I convert a dictionary to a JSON object in Python?
How to convert Python dictionary to JSON?
Advertisements
How do you sum a dictionary
Convert dictionary to JSON Python
Convert dictionary to JSON Python
How do you combine two dictionary values for common keys
How do I upgrade mysql?
how do i solve this problem?
How can I do it? .click();
how do i solve this question?
How to convert map to json in Java
How to convert map to json in Java
How do i do the coding for 'leaving a comment' in java
How do I decompile Java class files?
How do I initialize a byte array in Java?
How do I compare strings in Java?
How to dynamically build a JSON object with Python
How to dynamically build a JSON object with Python
how to convert json into dataframe in scala
Read JSON file into Python dictionary
Read JSON file into Python dictionary
How do I compile the registration form?
How do I get started with Bootstrap
How do I get started with Bootstrap
How do I learn Spring Framework?
How do I learn Spring Framework?
How do I learn Spring Framework?
How do I learn Spring Framework?
How do I learn Spring Framework?
How do I study big data?
How do I generate random number?

Ads