You are currently viewing Python json dumps() Function

The dumps() function is from the JSON module that is used to convert Python objects to JSON string objects. It takes python objects such as a dictionary, list, string, integer, float, boolean, and None and converts them into JSON strings.

Advertisements

Using some of its parameters we can avoid many errors while converting a specified Python object to a JSON string object.

In this article, I will explain Python json.dumps() method syntax, its parameters, and usage by using different options and finally converting python objects to JSON string very efficiently.

Related Article: Convert Python List to JSON

1. Syntax of json.dumps() in Python

Following is the syntax of 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)

1.1 Parameters of json.dumps()

Following are the parameters of json.dumps() method.

  • obj: Python object which is to be converted as a JSON string objcet. 
  • skipkeys: By default is False. Avoid TypeError by setting skipkeys = True, when we have dict keys which are not basic type(i.e. str, int, float, bool, None).
  • ensure_ascii: If ensure_ascii is True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is False, these characters will be output as-is. 
  • check_circular: If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
  • allow_nan: I (default: True), If it sets False then it will be given a ValueError to serialize out of range float values (nan, inf, -inf) . If allow_nan is True, their JavaScript equivalents (NaN, Infinity, -Infinity)
  • indent: If indent is a non-negative integer or string, then JSON array elements and object members will be printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as “\t”), that string is used to indent each level. 
  • separators: If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘, ‘, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘, ‘, ‘:’) to eliminate whitespace. 
  • default: If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised. 
  • sort_keys: If sort_keys is True (default: False), then the output of dictionaries will be sorted by key. 

1.3 Return Value

It returns a JSON string object.

2. Usage of json.dumps() Function

Python json.dumps() function is from the json module that is used to return JSON string object by taking any python object as its argument. Using its parameters we can implement the conversion from any python object to a JSON string object without getting errors. In this article, I will use a Python dictionary to convert JSON string object using the dumps() method.

Note: Before going to use the json.dumps() we have to import a json module.


# Import json module
import json

# Create dictionary
courses = { "course": "python",
         "fee": 4000,
         "duration": "30 days"}
print(type(courses))

# Convert dictionary to JSON object
json_obj = json.dumps(courses)
print(json_obj)
print(type(json_obj))

Yields below output. Note that type(json_obj) function returns a string type. This example converted the dictionary to a JSON string.

Python json dumps

3. Skip the Keys(Which are not basic type) Using json.dumps()

If we have dictionary keys that are not basic type(i.e. str, int, float, bool, None) when we want to convert it to JSON object using dumps() method, it will give Type Error. To skip the keys(which are not basic type) and avoid errors by setting the skipkeys as True(default: False).

Here, I will take a tuple of strings as a key of the dictionary to demonstrate this.


# Create dictionary
courses = { ('course', 'language'): "python",
         "fee": 4000,
         "duration": "30 days"}
print(type(courses))

# Skip the keys using json.dumps()
json_obj = json.dumps(courses, skipkeys = True)
print(json_obj)
print(type(json_obj))

Yields below output. Notice that all keys with tuples are ignored while converting to JSON string.

Python dumps json

4. Allow NaN Values using json.dumps() in Python

We can allow NaN values in a JSON string object using json.dumps() method. When the given dictionary has a float value of ‘nan‘ and using allow_nan = False param on dumps(), it will give ValueError. If we set allow_nan as True this is the default value, it will give the equivalent float value of ‘NaN in a JSON.


# Create dictionary
courses = { ('course', 'language'): "python",
         "fee": 4000,
         "duration": "30 days",
        "discount": float('nan')}
print((courses))

# Allow NaN Values using json.dumps()
json_obj = json.dumps(courses, skipkeys = True, allow_nan = True)
print(json_obj)
print(type(json_obj))

# Output:
# {('course', 'language'): 'python', 'fee': 4000, 'duration': '30 days', 'discount': nan}
# {"fee": 4000, "duration": "30 days", "discount": NaN}
# <class 'str'>

5. Improve Readability using Indent of json.dumps()

We can improve readability by providing an indent param with a specified integer. Set the indent param with a specified integer and pass it into the dumps() method, it will return the JSON object with a pretty print.


# Improve readability by using indent param
json_obj = json.dumps(courses, skipkeys = True, allow_nan = True, indent = 4)
print(json_obj)
print(type(json_obj))

# Output:
# {
#    "fee": 4000,
#   "duration": "30 days",
#    "discount": NaN
# }
# <class 'str'>

6. Use Separators using json.dumps() Method

By using the separators of dumps() method we can provide specific separators between items and after key/value pair of JSON object. These separators should be an (item_separator, key_separator) tuple. For example,


# Specify specific separators using dumps() 
json_obj = json.dumps(courses, skipkeys = True, 
         allow_nan = True, indent = 4, 
        separators =(". ", " = "))
print(json_obj)
print(type(json_obj))

# Output:
# {
#    "fee" = 4000. 
#    "duration" = "30 days". 
#    "discount" = NaN
#}
<class 'str'>

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 python 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 syntax, parameters, return type, and using its parameters how we can implement the conversion of Python objects to JSON string with examples.

Happy Learning!!

References