Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python json.encoder.encode_basestring() Function



The Pythonjson.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 Pythonjson.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 thejson.encoder.encode_basestring() function to encode a string with special characters −

import json.encoder# String with special characterstext = "Hello \"World\"\nNew Line"# Encode the stringencoded_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 stringdata = {    "message": "Hello, \"User\"!"}# Encode the message stringencoded_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 usingencode_basestring() function −

import json.encoder# String containing backslashestext = "Path: C:\\Users\\Admin"# Encode the stringencoded_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 stringtext = "First Line\nSecond Line\nThird Line"# Encode the stringencoded_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"
python_json.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp