Python json.encoder.encode_basestring() Function
The Python json.encoder.encode_basestring() function is used to encode a Python string into a JSON-compliant string.
This function ensures that special characters are properly escaped when encoding a string in JSON format.
Syntax
Following is the syntax of the Python json.encoder.encode_basestring() function β
json.encoder.encode_basestring(s)
Parameters
This function accepts the Python string as a parameter that needs to be encoded into a JSON-compatible format.
Return Value
This function returns a JSON-encoded string with proper escaping.
Example: Basic Usage
In this example, we use the json.encoder.encode_basestring() function to encode a string with special characters β
import json.encoder
# String with special characters
text = "Hello \"World\"\nNew Line"
# Encode the string
encoded_string = json.encoder.encode_basestring(text)
print("Encoded JSON String:", encoded_string)
Following is the output obtained β
Encoded JSON String: "Hello \"World\"\nNew Line"
Example: Using encode_basestring() for JSON Formatting
This function can be useful when formatting JSON data manually β
import json.encoder
# JSON data with a string
data = {
"message": "Hello, \"User\"!"
}
# Encode the message string
encoded_message = json.encoder.encode_basestring(data["message"])
print("Formatted JSON Message:", encoded_message)
We get the output as shown below β
Formatted JSON Message: "Hello, \"User\"!"
Example: Escaping Backslashes
Special characters like backslashes are properly escaped when using encode_basestring() function β
import json.encoder
# String containing backslashes
text = "Path: C:\\Users\\Admin"
# Encode the string
encoded_string = json.encoder.encode_basestring(text)
print("Encoded JSON String:", encoded_string)
The result produced is as follows β
Encoded JSON String: "Path: C:\\Users\\Admin"
Example: Encoding a Multi-line String
This example demonstrates how json.encoder.encode_basestring() function handles multi-line strings by properly escaping newline characters β
import json.encoder
# Multi-line string
text = "First Line\nSecond Line\nThird Line"
# Encode the string
encoded_string = json.encoder.encode_basestring(text)
print("Encoded JSON String:", encoded_string)
Following is the output of the above code β
Encoded JSON String: "First Line\nSecond Line\nThird Line"