Python json.encoder Attribute



The Python json.encoder attribute is a module-level component that provides functionalities for encoding Python objects into JSON-formatted strings.

This attribute is primarily used to convert Python data structures into JSON format, which can be useful for APIs, file storage, or data transmission.

Syntax

Following is the syntax of using the json.encoder attribute −

import json.encoder

Functions and Classes

The json.encoder attribute provides the following key functions and classes −

  • JSONEncoder: A class for encoding Python objects into JSON format.
  • encode_basestring: A function for encoding string values safely.
  • encode_basestring_ascii: A function that ensures ASCII encoding of strings.
  • escape_unicode: A function to escape non-ASCII characters.
  • make_iterencode: A function that generates an iterable JSON encoder.

Example: Using JSONEncoder

In this example, we use the JSONEncoder class to convert a Python dictionary into a JSON string −

import json

# Define Python dictionary
data = {"name": "John", "age": 30, "city": "New York"}

# Create JSONEncoder instance
encoder = json.encoder.JSONEncoder()

# Encode dictionary to JSON string
json_string = encoder.encode(data)

print("Encoded JSON:", json_string)

Following is the output obtained −

Encoded JSON: {"name": "John", "age": 30, "city": "New York"}

Example: Using encode_basestring() Function

The encode_basestring() function is used to safely encode string values −

import json.encoder

# Define a string
text = "Hello, World!"

# Encode string using encode_basestring
encoded_string = json.encoder.encode_basestring(text)

print("Encoded String:", encoded_string)

Following is the output of the above code −

Encoded String: "Hello, World!"

Example: Using encode_basestring_ascii() Function

The encode_basestring_ascii() function ensures ASCII encoding of string values −

import json.encoder

# Define a string with special characters
text = "Caf"

# Encode string using encode_basestring_ascii
encoded_ascii = json.encoder.encode_basestring_ascii(text)

print("ASCII Encoded String:", encoded_ascii)

We get the output as shown below −

ASCII Encoded String: "Caf\u00e9"

Example: Using JSONEncoder().iterencode() Function

The iterencode() method generates an iterable JSON-encoded output instead of returning a single string −

import json

# Define a Python dictionary
data = {"name": "Alice", "age": 28, "city": "Paris"}

# Create a JSONEncoder instance
encoder = json.JSONEncoder()

# Generate an iterable JSON encoding
json_iterable = encoder.iterencode(data)

# Print each part of the encoded JSON
print("Encoded JSON (Iterative Output):")
for chunk in json_iterable:
   print(chunk, end="")

The result produced is as follows −

Encoded JSON (Iterative Output):
{"name": "Alice", "age": 28, "city": "Paris"}
python_json.htm
Advertisements