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.
SyntaxFollowing is the syntax of using the json.encoder attribute −
import json.encoderFunctions and Classes
The json.encoder attribute provides the following key functions and classes −
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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4