How to convert a dictionary to JSON in python? We can use the json.dumps() method and json.dump() method to convert a dictionary to a JSON string.
JSON stands for JavaScript Object Notation and is used to store and transfer data in the form of text. It represents structured data. You can use it especially for sharing data between servers and web applications. Python has a built-in package called json to work with JSON file or strings. The data in the JSON is made up of the form of key/value pairs and they can be enclosed with {}. Look wise it is similar to a Python dictionary. But JSON keys must be sting-type objects with a double-quoted and values can be any datatype such as string, integer, nested JSON, a list, a tuple, or even another dictionary.
A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.
# Create dictionary
courses = { “course”: “python”,
“fee”: 4000,
“duration”: “30 days”}
print(courses)
1. Quick Examples of Converting Dictionary to JSON
Following are quick examples of converting a dictionary to JSON.
# Below are the quick examples.
# Example 1: Convert dictionary to JSON object
json_obj = json.dumps(courses, indent = 4)
# Example 2: Convert nested dictionary to JSON
json_obj = json.dumps(courses, indent = 4)
# Example 3: Convert dictionary to JSON array
array = [ {‘key’ : x, ‘value’ : courses[x]} for x in courses]
json_obj = json.dumps(array)
# Example 4: Convert dictionary to JSON object using sort_keys
json_obj = json.dumps(courses, indent = 4, sort_keys = True)
2. Convert Dictionary to JSON in Python
You can convert a Python dictionary (dict) to JSON using the json.dumps() method from json module, this function also takes a dictionary as an argument to convert it to JSON.
2.1 Syntax of json.dumps()
Following is the syntax of the the json.dumps()
# Syntax of json.dumps() function
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)
2.2 Parameters
This function takes two parameters.
dictionary: Name of a dictionary that should be converted to JSON object.
indent: Specifies the number of units we have to take for indentation.
2.3 Return Value
It returns a JSON string object.
3. Usage of dumps() to Convert Dictionary to JSON
json.dumps() function is json module of Python that is used to convert Python object(here, dictionary) to JSON object. This function is also used to convert data types such as a dictionary, list, string, integer, float, boolean, and None into JSON.
Note: Before going to use json.dumps() we have to import json module.
# Type of courses
print(type(courses))
# Convert dictionary to JSON object
import json
json_obj = json.dumps(courses, indent = 4)
print(json_obj)
print(type(json_obj))
Yields below output.
4. Convert Python Nested Dictionary to JSON
Let’s use another example with a nested dictionary and convert to JSON using json.dumps() function. A dictionary inside another dictionary is called a nested dictionary. To convert the nested dictionary into a JSON object, we have to pass the given dictionary and indent param into dumps() function. It will convert the nested dictionary into a JSON objects with specified indentation.
For example,
# Create nested dictionary
import json
courses = {
“Python”: {“year”: 1991,
“creator”: “G. van Rossum” },
“Java”: {“year”: 1995,
“creator”: “J. Gosling”},
}
print(courses)
# Convert nested dictionary to json
json_obj = json.dumps(courses, indent = 4)
print(json_obj)
print(type(json_obj))
Yields below output.
5. Convert Dictionary to JSON Array
Let’s create an array of dictionaries using dictionary comprehension and then convert the array to a JSON array. For example,
# Convert dictionary to JSON array
array = [ {‘key’ : x, ‘value’ : courses[x]} for x in courses]
print(json.dumps(array))
print(type(json.dumps(array)))
# Output:
# [{“key”: “course”, “value”: “python”}, {“key”: “fee”, “value”: 4000}, {“key”: “duration”, “value”: “30 days”}]
<class ‘str’>
6. Convert Dictionary to JSON Quotes
First, we can create a class using the __str__(self) method which is used for string representation to convert a dictionary into a JSON object. Then we create a variable with single quoted values and declare it as a dictionary using str(self) method. Finally, using the dumps() function we can convert the dictionary to JSON quotes(which means double quoted). For example,
# Convert dictionary to JSON quotes
import json
# create a class using the __str__(self) method
class courses(dict):
def __str__(self):
return json.dumps(self)
# using the json.dumps() function
# to convert dictionary to JSON quotes
list = [[‘Python’, ‘Pandas’]]
print(“The dictionary: n”, list)
json_obj = courses(list)
print(“The json object:”, json_obj)
# Output:
# The dictionary:
# [[‘Python’, ‘Pandas’]]
# The json object: {“Python”: “Pandas”}
7. Convert Sorted Dictionary to JSON using sort_keys
Set sort_keys() param as True and then pass it into the dumps() method along with given dictionary and indent param, it will sort the dictionary and convert it into a JSON object.
# Convert dictionary to JSON object using sort_keys
json_obj = json.dumps(courses, indent = 4, sort_keys = True)
print(json_obj)
# Output:
# {
# “course”: “python”,
# “duration”: “30 days”,
# “fee”: 4000
#}
8. Conclusion
In the article, I have explained json.dumps() function and using its parameters how we can convert the dictionary to JSON in python with examples.
Happy Learning!!
References
https://docs.python.org/3/library/json.html
How to convert a dictionary to JSON in python? We can use the json.dumps() method and json.dump() method to convert a dictionary to a JSON string. JSON stands for JavaScript Object Notation and is used to store and transfer data in the form of text. It represents structured data. You can use it especially for sharing data Read More Python, Python Tutorial, Python JSON Examples