You are currently viewing Convert Python Dictionary to JSON

How to convert a dictionary to JSON in Python? We can use the json.dump() method and json.dumps() method to convert a dictionary to a JSON string.

Advertisements

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.

Related: You can convert Json object to Python dictionary.


# 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.dump() method and json.dumps() method from json module, these functions also take a dictionary as an argument to convert it to JSON.

2.1 Syntax of json.dump() Method

Following is the syntax of json.dump() method.


# Syntax of json.dump() function
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

2.1.1 Parameters

This function allows the following 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.1.2 Return Value

It returns a JSON string object.

2.1.3 Using json.dump() to Write JSON Data to a File in Python

Let’s see an example of writing a Python object to a JSON file. The data parameter represents the JSON data to be written to the file. This can be any Python object that is JSON serializable, such as a dictionary or a list. Alternatively, you can also put this data to a file and read json from a file into a object.

Following is the syntax of writing JSON data to file.


# Syntax of write JSON data to file
import json
with open("data.json", "w") as outfile:
    # json_data refers to the above JSON
    json.dump(json_data, outfile)

where:

  • json_data is the Python object to be encoded as JSON.
  • "data.json" is the name of the file where the JSON data will be written.
  • "w" specifies that the file will be opened in write mode.
  • outfile is the file-like object where the JSON data will be written.

Here, in the below example json_data is a dictionary object which I will write to a file.


# Import json module
import json

# Create dictionary object which is json representation
json_data = {
    "name": "Python",
    "year": 1991,
    "creator": "Guido van Rossum",
    "popular": True
}

# Writing JSON data to a file using a file object
with open("data.json", "w") as outfile:
    # json_data refers to the above JSON
    json.dump(json_data, outfile)

As you can see from the above, the JSON file has been returned from JSON data. When we want to see the JSON data on the console you can use json.dumps() function. It will return the JSON data from the Python object.

2.2 Syntax of json.dumps()

Following is the syntax of 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.1 Parameters

This function allows the following 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.2.2 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.

Python convert dictionary JSON

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 object 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.

Python convert nested dictionary JSON

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

# Create a class using the  __str__(self) method 
import json 
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