Python json.dumps() Method: Complete Guide

0
311
Python json.dumps()

JSON is a convenient format for data exchange, which JavaScript influences. JSON is generally in a string or text format and stands for JavaScript Object Notation.

To encode or convert a Python object into a JSON string, use the json.dumps() method. The

Python json.dumps()

The json.dumps() is a built-in Python function that encodes any data to JSON, and the operation is called a json encoding. The json.dumps() function transforms the dictionary object into the JSON string data format.

Syntax

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)

Parameters

obj: It serializes the obj as a JSON formatted stream.

skipkeys: The default parameter for skipkeys is False, but if it is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

ensure_ascii: The default value for ensure_ascii is True, and the output is assured of having all incoming non-ASCII characters escape.

check_circular: The default value for check_circular is True, and if it is False, then the circular reference check for container types will be skipped, and a circular reference will result in an OverflowError.

allow_nan: The default value for check_circular is True, and if it is False, then it will be a ValueError to serialize out-of-range float values (nan, inf, -inf) in strict acquiescence with the JSON specification.

indent: 

  1. If the indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level.
  2. An indent level of 0, negative, or ” ” will only insert new lines. None (the default) selects the most compact representation.
  3. A positive integer indent indents that many spaces per level. If the 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 the indent is None and (‘, ‘, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘, ‘, ‘:’) to trim whitespace.

Default: If specified, the default should be a function 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: The sort_keys parameter value is False by default, but if it is true, then the output of dictionaries will be sorted by key.

Example

Write the following code that demonstrates that json.dumps() method.

import json

# Creating a dictionary
dict = {'Name': 'Mandalorian', 'Season': 'Two', 'Episode': 'First'}

# Converts input dict to string and saves it in json_string
json_string = json.dumps(dict)
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps()
print(type(json_string))

Output

Equivalent json string of input dictionary: {"Name": "Mandalorian", "Season": "Two", "Episode": "First"}
<class 'str'>

You can see that the output is json string from the dictionary.

Pass skipkeys to True in json.dumps()

If you pass skipkeys = True in json.dumps() method, skips the keys that are not of the basic data type. For example, list, tuple, or set is not a basic data type, while integer, string, and boolean are basic data types.

# app.py

import json

# Creating a dictionary
dict = {
    ('x', 'y', 'z'): 'Elder Wand',
    2: 'Expecto',
    3: 'Patronum',
    4: 'Avada',
    5: 'Kedavra'
}

# Converts input dictionary into string and stores it in json_string
json_string = json.dumps(dict, skipkeys=True)
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps
print(type(json_string))

Output

Equivalent json string of input dictionary: {"2": "Expecto", "3": "Patronum", "4": "Avada", "5": "Kedavra"}
<class 'str'>

You can see that the dictionary’s first key is a tuple, which is not the basic data type. That is why, in the output, it is skipped.

Passing the out-of-range float values

To pass the out of range float values, use the float() method. Define the float(‘nan’) value in the dictionary and pass the allow_nan = True to the dumps() method.

# app.py

import json

# Creating a dictionary
dict = {
    ('x', 'y', 'z'): 'Elder Wand',
    2: 'Expecto',
    3: 'Patronum',
    4: float('nan')
}

# Converts input dictionary into string and stores it in json_string
json_string = json.dumps(dict, skipkeys=True, allow_nan=True)
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps
print(type(json_string))

Output

Equivalent json string of input dictionary: {"2": "Expecto", "3": "Patronum", "4": NaN}
<class 'str'>

Passing an indent parameter to json.dumps()

If you pass the indent as a parameter, it will return the indented string.

# app.py

import json

# Creating a dictionary
dict = {
    ('x', 'y', 'z'): 'Elder Wand',
    2: 'Expecto',
    3: 'Patronum',
    4: float('nan')
}

# Converts input dictionary into string and stores it in json_string
json_string = json.dumps(dict,
                         skipkeys=True,
                         allow_nan=True,
                         indent=4)
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps
print(type(json_string))

Output

Equivalent json string of input dictionary: {
    "2": "Expecto",
    "3": "Patronum",
    "4": NaN
}
<class 'str'>

For json pretty print, pass the parameter ‘indent’ to the json.dumps() function.

Passing the separators

If you specify the separators, it should return an (item_separator, key_separator) tuple, and items are separated by ‘.’ and key values are separated by ‘=’.

import json

# Creating a dictionary
dict = {
    ('x', 'y', 'z'): 'Elder Wand',
    2: 'Expecto',
    3: 'Patronum',
    4: float('nan')
}

# Converts input dictionary into string and stores it in json_string
json_string = json.dumps(dict,
                         skipkeys=True,
                         allow_nan=True,
                         indent=4,
                         separators=(". ", " = "))
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps
print(type(json_string))

Output

Equivalent json string of input dictionary: {
    "2" = "Expecto".
    "3" = "Patronum".
    "4" = NaN
}
<class 'str'>

Order the result

The json.dumps() method has a parameter called sort_keys() to order the keys in the result.

import json

# Creating a dictionary
dict = {
    11: 'Elder Wand',
    21: 'Expecto',
    13: 'Patronum',
    41: float('nan')
}

# Converts input dictionary into string and stores it in json_string
json_string = json.dumps(dict,
                         skipkeys=True,
                         allow_nan=True,
                         indent=4,
                         separators=(". ", " = "),
                         sort_keys=True)
print('Equivalent json string of input dictionary:', json_string)

# Checking type of object returned by json.dumps
print(type(json_string))

Output

Equivalent json string of input dictionary: {
    "11" = "Elder Wand".
    "13" = "Patronum".
    "21" = "Expecto".
    "41" = NaN
}
<class 'str'>

Conclusion

The json.dumps() function creates a json object. The json.dump() method creates a JSON File using File I/O of Python. The json.dumps() method converts a Python object into a json string. The json.loads() function decoding JSON String in Python dictionary.

That’s it.

See also

Python json.load()

Python dict to json

Python json to dict

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.