Сохранение символов Юникода в парах ключ/значение JSON в Python

Чтобы предоставить действительный JSON-эквивалент пары ключ/значение, сохраняя при этом исходное значение в Python, вы можете использовать модуль json. Вот несколько способов добиться этого:

Метод 1: использование json.dumps()

import json
key = u"(If it's not English, please translate it into English.)"
value = "Your original value"
# Create a dictionary with the key/value pair
data = {key: value}
# Convert the dictionary to a JSON string while preserving the Unicode characters
json_data = json.dumps(data, ensure_ascii=False)
print(json_data)

Метод 2. Использование специального класса кодировщика

import json
class UnicodeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, str):
            return obj.encode('utf-8').decode('unicode-escape')
        return super().default(obj)
key = u"(If it's not English, please translate it into English.)"
value = "Your original value"
# Create a dictionary with the key/value pair
data = {key: value}
# Convert the dictionary to a JSON string using the custom encoder class
json_data = json.dumps(data, cls=UnicodeEncoder)
print(json_data)