- Advertisement -Newspaper WordPress Theme
otherjson.dumps in Python

json.dumps in Python

Introduction

JSON, which stands for JavaScript Object Notation, is a widely-used format for sending, receiving, and storing data. In Python, the json module is dedicated to handling JSON data. JSON data consists of key-value pairs enclosed in curly braces or square brackets, similar to Python dictionaries.

The json.dump function in Python is used to serialize Python objects into a JSON formatted stream.

Syntax

python

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)

Parameters and Functionality

  • obj: The Python object to be serialized into JSON.
  • skipkeys: If True, dictionary keys that are not of a basic type will be skipped. Default is False.
  • ensure_ascii: If True (default), non-ASCII characters are escaped in the output. If False, non-ASCII characters will be output as-is.
  • check_circular: If False, the check for circular references in container types is skipped. Default is True.
  • allow_nan: If False, it raises a ValueError when serializing out-of-range float values (nan, inf, -inf). Default is True, which uses JavaScript equivalents (NaN, Infinity, -Infinity).
  • indent: If a non-negative integer or string, JSON array elements and object members will be pretty-printed with that indent level.
  • separators: Specifies item and key separators. Default is (", ", ": ").
  • default: A function called for objects that can’t 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 True, the output of dictionaries will be sorted by key. Default is False.

Examples

Example 1: Basic Usage

Passing a Python dictionary to json.dumps returns a JSON string.

python

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:

arduino

Result of passing through json.dumps: {"1": "Board", "2": "Infinity", "3": "Forever"}
<class 'str'>

Example 2: Using skipkeys

Setting skipkeys to True skips non-basic type keys.

python

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:

arduino

Result of passing through json.dumps: {"1": "Board", "2": "Infinity", "3": "Forever"}
<class 'str'>

Example 3: Using allow_nan

Setting allow_nan to True allows the serialization of NaN values.

python

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:

arduino

Result of passing through json.dumps: {"1": "Board", "2": "Infinity", "3": "NaN"}
<class 'str'>

Additional Information

Formatting the Result

The json module provides built-in methods for formatting the result. The indent parameter determines the indentation level for pretty-printing.

python

json.dumps(y, indent=5)

You can also define custom separators to separate objects. By default, separators are (", ", ": ").

python

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

Ordering the Result

The result of json.dumps can be ordered by setting the sort_keys parameter to True.

python

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

Conclusion

By the end of this section, you should understand what JSON is and how to convert Python objects to JSON format. Additionally, you will be familiar with the various parameters of the json.dump function and their effects on the output.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe Today

GET EXCLUSIVE FULL ACCESS TO PREMIUM CONTENT

SUPPORT NONPROFIT JOURNALISM

EXPERT ANALYSIS OF AND EMERGING TRENDS IN CHILD WELFARE AND JUVENILE JUSTICE

TOPICAL VIDEO WEBINARS

Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

Exclusive content

- Advertisement -Newspaper WordPress Theme

Latest article

More article

- Advertisement -Newspaper WordPress Theme