Site icon Spark By {Examples}

Python json dumps() Function

Python json dumps

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.

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.

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

Exit mobile version