Python json.encoder.encode_basestring_ascii() Function



The Python json.encoder.encode_basestring_ascii() function is used to encode a Python string into a JSON-compliant ASCII string.

This function ensures that all non-ASCII characters are escaped using Unicode escape sequences.

Syntax

Following is the syntax of the Python json.encoder.encode_basestring_ascii() function −

json.encoder.encode_basestring_ascii(s)

Parameters

This function accepts the Python string as a parameter that needs to be encoded into a JSON-compatible ASCII format.

Return Value

This function returns an ASCII-encoded JSON string with proper escaping.

Example: Basic Usage

In this example, we use the json.encoder.encode_basestring_ascii() 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_ascii(text)

print("Encoded ASCII JSON String:", encoded_string)

Following is the output obtained −

Encoded ASCII JSON String: "Hello \"World\"\nNew Line"

Example: Encoding a Multi-line String

This example demonstrates how json.encoder.encode_basestring_ascii() 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_ascii(text)

print("Encoded JSON String:", encoded_string)

Following is the output of the above code −

Encoded JSON String: "First Line\nSecond Line\nThird Line"

Example: JSON Formatting

This function can be useful when formatting JSON data manually while ensuring ASCII compatibility −

import json.encoder

# JSON data with a string
data = {
   "message": "Hello, \"User\"!"
}

# Encode the message string
encoded_message = json.encoder.encode_basestring_ascii(data["message"])

print("Formatted ASCII JSON Message:", encoded_message)

We get the output as shown below −

Formatted ASCII JSON Message: "Hello, \"User\"!"

Example: Escaping Non-ASCII Characters

Non-ASCII characters are properly escaped when using the encode_basestring_ascii() function −

import json.encoder

# String containing non-ASCII characters
text = "Piata "

# Encode the string
encoded_string = json.encoder.encode_basestring_ascii(text)

print("Encoded ASCII JSON String:", encoded_string)

The result produced is as follows −

Encoded ASCII JSON String: "Pi\u00f1ata \ud83c\udf89"
python_json.htm
Advertisements