- Python json dumps() Function
- 1. Syntax of json.dumps() in Python
- 1.1 Parameters of json.dumps()
- 1.3 Return Value
- 2. Usage of json.dumps() Function
- 3. Skip the Keys(Which are not basic type) Using json.dumps()
- 4. Allow NaN Values using json.dumps() in Python
- 5. Improve Readability using Indent of json.dumps()
- 6. Use Separators using json.dumps() Method
- 7. Convert Sorted Dictionary to JSON using sort_keys
- 8. Conclusion
- References
- You may also like reading:
- You Must Know Python JSON Dumps, But Maybe Not All Aspects
- Some tricks about the dump(s) method of the Python JSON module
- Table of Content
- 0. Differences between “dump” and “dumps”
- Python json dumps separators
- # Using json.dumps() without Spaces in Python
- # Adding spaces only between the keys and the values
- # Adding spaces only between the key-value pairs
- # Additional Resources
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.
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.
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.
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.
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># #
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 # >#
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: #
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: #
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.
References
You may also like reading:
You Must Know Python JSON Dumps, But Maybe Not All Aspects
Some tricks about the dump(s) method of the Python JSON module
Python has built-in support to JSON documents, by its “json” module. I bet most of us have used it, and some of us have used it a lot. We know that we can use the json.dumps() method to easily convert a Python dictionary object into a JSON string. However, this method is not that simple as most developers thought.
In this article, I’ll introduce this json.dumps() method by examples. The complexity and rarity of usage are from shallow to deep.
Now we should begin. No need to download anything, your Python 3.x must come with the JSON module.
Table of Content
0. Differences between “dump” and “dumps”
In case some newbies are reading this article, it is probably necessary to mention that there are two similar methods in the JSON module — dump() and dumps() .
These two methods have almost identical signatures, but dump() writes the converted JSON string to a stream (usually a file), whereas dumps() convert the dictionary into a JSON string only.
Suppose we have a simple dictionary as follows.
my_dict = 'name': 'Chris',
'age': 33
>
If we want to convert it to a formatted JSON string and write it to a file, we can use dumps() .
with open('my.json', 'w') as f:
json.dump(my_dict, f)
Then, if we check the working directory, the file my.json should be there with the converted JSON string.
Python json dumps separators
Last updated: Feb 20, 2023
Reading time · 2 min
# Using json.dumps() without Spaces in Python
Use the separators keyword argument to use the json.dumps() method without spaces.
The separators argument can be set to a tuple containing a comma and a colon to remove the whitespace.
Copied!import json employee = 'name': 'Bobby', 'age': 30, 'salary': 100, > # 👉️ default separators are (', ', ': ') # ✅ JSON string without spaces json_str = json.dumps(employee, separators=(',', ':')) print(json_str) # 👉️ '' # ----------------------------------------------- # ✅ JSON string with spaces only between keys and values json_str = json.dumps(employee, separators=(',', ': ')) print(json_str) # ✅ '' # ----------------------------------------------- # ✅ JSON string with spaces only between key-value pairs json_str = json.dumps(employee, separators=(', ', ':')) print(json_str) # ✅ ''
We used the separator keyword argument to add no extra whitespace to the output of the json.dumps() method.
The json.dumps method converts a Python object to a JSON formatted string.
The separators argument is a tuple containing 2 values — the separator between each key-value pair and the separator between each key and value.
The default value for the argument is (‘, ‘, ‘: ‘) if the indent argument is None and (‘,’, ‘: ‘) if indent is set to any other value.
Copied!import json employee = 'name': 'Bobby', 'age': 30, 'salary': 100, > # 👇️ default behavior print(json.dumps(employee)) # 👇️ print(len(json.dumps(employee))) # 👉️ 43 # 👇️ with whitespace removed json_str = json.dumps(employee, separators=(',', ':')) print(json_str) # 👉️ '' print(len(json_str)) # 👉️ 38
If you still get whitespace when converting to JSON, make sure you aren’t passing a value for the indent argument.
Copied!import json employee = 'name': 'Bobby', 'age': 30, 'salary': 100, > # # "name":"Bobby", # "age":30, # "salary":100 # > json_str = json.dumps(employee, indent=4, separators=(',', ':')) print(len(json_str)) # 👉️ 54
The indent keyword argument pretty prints the JSON string with the specified indent level. The argument is set to None by default.
To remove all whitespace from the JSON string, either set the indent argument to None or omit it when calling json.dumps() .
# Adding spaces only between the keys and the values
If you need to add whitespace only between the keys and the values, set the separator to a colon and a space.
Copied!import json employee = 'name': 'Bobby', 'age': 30, 'salary': 100, > json_str = json.dumps(employee, separators=(',', ': ')) print(json_str) # 👉️ '' print(len(json_str)) # 👉️ 41
# Adding spaces only between the key-value pairs
Similarly, if you need to add a space only between the key-value pairs, set the separator to a comma and a space.
Copied!import json employee = 'name': 'Bobby', 'age': 30, 'salary': 100, > json_str = json.dumps(employee, separators=(', ', ':')) print(json_str) # 👉️ '' print(len(json_str)) # 👉️ 40
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.