JSON Python

json.dumps in Python

json.dumps in Python

Introduction

JSON is an acronym that represents JavaScript Object Notation. It is a language format that is primarily used to send and receive data between systems and store data in certain cases as well. Python contains a separate package called JSON for the handling of JSON data. JSON data comprises data in terms of key-value pairs delimited by square brackets or curly braces similar to a dictionary which also consists of comma-separated key-value pairs.

json.dump is a function of Python which is used to convert a set of Python objects to a JSON string

Syntax

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)

Parameter

Functionality

obj

Serialize obj as a JSON formatted stream to fp

skipkeys

If skipkeys is True, dictionary keys which are not of basic type will be skipped

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 a Recursion Erro (or worse).

allow_nan

If allow_nan is false (default: True), then it will be a ValueError to serialize out-of-range float values (nan, inf, -inf) in strict compliance with the JSON specification. If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used

indent

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level

separators

If specified, separators should be an(item_separator,key_separator)

default

If specified, the 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.

Examples

Example 1

A string is returned when a Python dictionary is passed to json.dumps() function

import json

# Creating a dictionary
d ={1:'Board', 2:'Infinity',3:'Forever'}


json_str = json.dumps(d)
print('Result of passing through json.dumps',json_str)
print()

# Checking type of object

print(type(json_str))

Output:

Result of passing through json.dumps{"1" : "Board", "2" : "Infinity", "3" : "Forever"}

<class 'str'>

Example 2

In this case, we set skipkeys as true, as a result, the key of list type will be skipped and not be included

import json

# Creating a dictionary
d ={(45,67,86): 'Hello',1:'Board', 2:'Infinity',3:'Forever'}


json_str = json.dumps(d,skipkeys= True)
print('Result of passing through json.dumps',json_str)
print()

# Checking type of object
print(type(json_str))

Output:

Result of passing through json.dumps{"1" : "Board", "2" : "Infinity", "3" : "Forever"}

<class 'str'>

Example 3

In order to accept NaN values from the user, the allow_nan parameter of the function must be set to True, otherwise Python would throw an error

import json

# Creating a dictionary
d ={(45,67,86):'Hello',1:'Board', 2:'Infinity',3:'Forever',4:float('nan')}


json_str = json.dumps(d,skipkeys= True,allow_nan = True)
print('Result of passing through json.dumps',json_str)
print()

# Checking type of object

print(type(json_str))

Output:

Result of passing through json.dumps{"1" : "Board", "2" : "Infinity", "3" : "NaN"}

<class 'str'>

Additional Information

Formatting the Result

The JSON package in Python provides inbuilt methods to format the result by specifying the indent parameter. The indent parameter determines the space to be left from the margin. This space is left every time and the required data is printed. The syntax is given by:

json.dumps(y , indent = 5)

Similarly, we can also define separators, to separate each object using a comma and space or colon and a space. By default, the value of the separator is (", ", ": "). The required syntax is given below

json.dumps(y, indent = 5, separators = ("." , " = "))

Ordering the Result

The result of json.dumps() can be reordered by setting the sort_keys parameter to True

json.dumps(y, indent= 5, sort_keys=True)

Conclusion

Thus, at the end of this section, you will be able to understand what JSON is and understand the conversion of Python objects to JSON format. In addition, you will be familiarized with what each parameter means and what changing its value does.