We can convert python dict to json using json.dumps() function. Actually json.dumps() accepts python dict as an argument. This function returns a JSON object. In this article, We will see the implementation stepwise.
1. How to Convert python dict to JSON?
Firstly, We will create a python dictionary in step 1. In Step 2, we will convert it into a JSON object.
Step 1:
Here we will convert a python dictionary with some keys and values.
#sample python dictionary
python_dict = {
"key1": "Value1",
"key2": "Value2",
"key3": "Value3",
}
Step 2:
Let’s use json.dumps() function. But as it is the part of JSON module. Hence we need to import it before using it. Let’s see how?
import json
JSON_obj=json.dumps(python_dict)
Complete code with Output –
Here is the complete code with its output.
import json
#sample python dictionary
python_dict = {
"key1": "Value1",
"key2": "Value2",
"key3": "Value3",
}
#Converting Python dict to JSON
JSON_obj=json.dumps(python_dict)
#printing the JOSN object
print(JSON_obj)
Dictionary to Json ( Formatting)-
Till now, We have seen the conversion. Now we will see how can we format the JSON response.
1.1 indent:
We can use the indent parameter for improving indentation. Here we can provide values as an integer. Let’s see an example.
JSON_obj=json.dumps(python_dict, indent=6)
print(JSON_obj)
1.2 sort_keys:
This parameter is for sorting the keys of the JSON. We can have the syntax for better understanding.
JSON_obj=json.dumps(python_dict, sort_keys=True)
1.3 separators:
We can use the separators for changing the default separator.
JSON_obj=json.dumps(python_dict, separators=(". ", " = "))
Well, this seems a little confusing. Because of three consecutive values as parameter. No problem! Actually, It will use “.” in the place of “,” for separating objects. It will use “=” in the place of “:” for separating keys with values.
import json
#sample python dictionary
python_dict = {
"key1": "Value1",
"key2": "Value2",
"key3": "Value3",
}
JSON_obj=json.dumps(python_dict, separators=(". ", " = "))
print(JSON_obj)
2. How to convert dict to JSON file ?
Here we will use json.dump() function in the place of json.dumps(). Lets see the implemention.
import json
#sample python dictionary
python_obj = {"key1": "Value1","key2": "Value2", "key3": "Value3"}
with open("generated.json", "w") as f:
json.dump(python_obj, f)
3. How to Convert JSON to Dict ?
We can convert JOSN object to dict using the json.loads() function. Implementation wise It is very easy and self-explanatory.
import json
#sample python dictionary
JOSN_obj = '{"key1": "Value1","key2": "Value2", "key3": "Value3"}'
python_obj=json.loads(JOSN_obj)
print(python_obj)
I hope now can easily perform the JSON to dict conversion and vice versa also. Please comment on your views on the comment box.
Thanks
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.