The Wayback Machine - https://web.archive.org/web/20241009162519/https://www.geeksforgeeks.org/python-encode-unicode-and-non-ascii-characters-into-json/
Open In App

Python Encode Unicode and non-ASCII characters into JSON

Last Updated : 08 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article will provide a comprehensive guide on how to work with Unicode and non-ASCII characters in Python when generating and parsing JSON data. We will look at the different ways to handle Unicode and non-ASCII characters in JSON. By the end of this article, you should have a good understanding of how to work with Unicode and non-ASCII characters in JSON using Python. Also, we are going to cover the following topics related to encoding and serializing Unicode and non-ASCII characters in Python:

  1. How to encode Unicode and non-ASCII characters into JSON in Python.
  2. How to save non-ASCII or Unicode data as-is, without converting it to a \u escape sequence, in JSON.
  3. How to serialize Unicode data and write it into a file.
  4. How to serialize Unicode objects into UTF-8 JSON strings, instead of \u escape sequences.
  5. How to escape non-ASCII characters while encoding them into JSON in Python.

What is a UTF-8 Character?

Unicode is a standardized encoding system that represents most of the world’s written languages. It includes characters from many different scripts, such as Latin, Greek, and Chinese, and is capable of representing a wide range of characters and symbols. Non-ASCII characters are characters that are not part of the ASCII (American Standard Code for Information Interchange) character set, which consists of only 128 characters.

UTF-8 is a character encoding that represents each Unicode code point using one to four bytes. It is the most widely used character encoding for the Web and is supported by all modern web browsers and most other applications. UTF-8 is also backward-compatible with ASCII, so any ASCII text is also a valid UTF-8 text.

What is JSON?

The JSON module is a built-in module in Python that provides support for working with JSON (JavaScript Object Notation) data. It provides methods for encoding and decoding JSON objects, as well as for working with the data structures that represent them. The json.dumps() method is a method of the JSON module that serializes an object (e.g. a Python dictionary or list) to a JSON-formatted string. This string can then be saved to a file, sent over a network connection, or used in any other way that requires the data to be represented as a string.

Example 

BHere is how you could use the json.dumps() method to encode a Python dictionary as a JSON string.

Python3




import json
 
# Define a dictionary
my_dict = {
    "name": "John Doe",
    "age": 35,
    "email": "john.doe@example.com"
}
 
# Use the json.dumps() method to encode
# the dictionary as a JSON string
json_str = json.dumps(my_dict)
 
# Print the JSON string
print(json_str)


Output:

{"name": "John Doe", "age": 35, "email": "john.doe@example.com"}

Save non-ASCII or Unicode data as-is, not as \u escape sequence in JSON

By default, Python’s JSON module converts non-ASCII and Unicode characters into the \u escape sequence when encoding them into JSON data. This escape sequence consists of a backslash followed by a u and four hexadecimal digits, which represent the Unicode code point of the character. To save non-ASCII or Unicode characters as-is, without the \u escape sequence, you can use the json.dumps() function with the ensure_ascii parameter set to False. This will allow the JSON module to preserve the original encoding of the characters when generating the JSON data.

Python3




import json
 
data = {'name': 'école'}
 
# Encode the data with the ensure_ascii parameter set to False
json_data = json.dumps(data, ensure_ascii=False)
 
print(json_data)


Output:

{"name": "école"}

JSON Serialize Unicode Data and Write it into a file

To serialize Unicode data and write it to a file in JSON format, you can use the json.dump() function. This function takes a Python object and a file object encodes the object into JSON data and writes it to the file.

Python3




import json
 
data = {'name': 'école'}
 
# Open a file for writing
with open('data.json', 'w', encoding='utf-8') as f:
    # Serialize the data and write it to the file
    json.dump(data, f, ensure_ascii=False)


Output:

Serialize Unicode objects into UTF-8 JSON strings instead of \u escape sequence

By default, the JSON module encodes Unicode objects (such as str and Unicode) into the \u escape sequence when generating JSON data. However, you can serialize Unicode objects into UTF-8 JSON strings by using the json.dumps() function with the encoding parameter set to ‘UTF-8’.

Python3




import json
 
data = {'name': 'école'}
 
# Encode the data with the encoding parameter set to 'utf-8'
json_data = json.dumps(data, encoding='utf-8', ensure_ascii=False)
 
print(json_data)


Output: 

{"name": "école"}

Encode both Unicode and ASCII into JSON

Here is an example of how to encode both Unicode and ASCII characters into JSON data using the json.dumps() function.

Python3




import json
 
data = {'name': 'école',
        'location': 'New York'}
 
# Encode the data with the ensure_ascii
# parameter set to False
json_data = json.dumps(data,
                       ensure_ascii=False)
 
print(json_data)


Output: 

{"name": "école", "location": "New York"}

Python Escape non-ASCII characters while encoding them into JSON:

To escape non-ASCII characters while encoding them into JSON data, you can use the json.dumps() function with the ensure_ascii parameter set to True. This will cause the JSON module to convert all non-ASCII characters into the \u escape sequence.

Python3




import json
 
data = {'name': 'école'}
 
# Encode the data with the ensure_ascii
# parameter set to True
json_data = json.dumps(data,
                       ensure_ascii=True)
 
print(json_data)


Output:

{"name": "\u00e9cole"}


Similar Reads

Encode an ASCII string into Base-64 Format
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML. Problem with sending normal binary data to a network is th
15+ min read
How To Fix - UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128) in Python
Several errors can arise when an attempt to change from one datatype to another is made. The reason is the inability of some datatype to get casted/converted into others. One of the most common errors during these conversions is Unicode Encode Error which occurs when a text containing a Unicode literal is attempted to be encoded bytes. This article
2 min read
Convert Unicode to ASCII in Python
Unicode is the universal character set and a standard to support all the world's languages. It contains 140,000+ characters used by 150+ scripts along with various symbols. ASCII on the other hand is a subset of Unicode and the most compatible character set, consisting of 128 letters made of English letters, digits, and punctuation, with the remain
2 min read
Check if a string contains a non-ASCII value in Julia - ascii() Method
The ascii() is an inbuilt function in Julia which is used to convert a specified string to a String type and also check the presence of ASCII data. If the non-ASCII byte is present, throw an ArgumentError indicating the position of the first non-ASCII byte. Syntax: ascii(s::AbstractString) Parameters:s::AbstractString: Specified stringReturns: It r
1 min read
Program to Convert ASCII to Unicode
In this article, we will learn about different character encoding techniques which are ASCII (American Standard Code for Information Interchange) and Unicode (Universal Coded Character Set), and the conversion of ASCII to Unicode. Table of Content What is ASCII Characters?What is ASCII Table?What is Unicode?Need for ASCII to Unicode ConversionAlgor
4 min read
Program to Convert Unicode to ASCII
Given a Unicode number, the task is to convert this into an ASCII (American Standard Code for Information Interchange) number. ASCII numberASCII is a character encoding standard used in communication systems and computers. It uses 7-bit encoding to encode 128 different characters 0-127. These values generally include numbers, letters, punctuation,
4 min read
Change Unicode to ASCII Character using Unihandecode
Unicode is generally represented as "\u4EB0\U5317" but this is nearly useless to a user who actually wants to read the real stuff what the text says. So in this article, we will see how to convert Unicode to ASCII Character using the Unihandecode module. What is Unihandecode?Unihandecode provide a function " decode (......) " that takes Unicode dat
1 min read
ASCII Vs UNICODE
Overview :Unicode and ASCII are the most popular character encoding standards that are currently being used all over the world. Unicode is the universal character encoding used to process, store and facilitate the interchange of text data in any language while ASCII is used for the representation of text such as symbols, letters, digits, etc. in co
3 min read
Transliterating non-ASCII characters with Python
Transliteration is a process of writing the word of one language using similarly pronounced alphabets in other languages. It deals with the pronunciation of words in other languages. Similarly, in computer language, the computer can handle ASCII characters but has problems with non-ASCII characters. There are some times when we are unable to skip n
3 min read
ASCII NULL, ASCII 0 ('0') and Numeric literal 0
The ASCII (American Standard Code for Information Interchange) NULL and zero are represented as 0x00 and 0x30 respectively. An ASCII NULL character serves as a sentinel character of strings in C/C++. When the programmer uses '0' in his code, it will be represented as 0x30 in hex form. What will be filled in the binary integer representation in the
3 min read
How to use Unicode and Special Characters in Tkinter ?
Prerequisite: Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we wi
1 min read
How to remove all Non-ASCII characters from the string using JavaScript ?
In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsing ASCII values with the Array filter methodApproa
3 min read
What is ASCII - A Complete Guide to Generating ASCII Code
The American Standard Code for Information Interchange, or ASCII, is a character encoding standard that has been a foundational element in computing for decades. It plays a crucial role in representing text and control characters in digital form. Historical BackgroundASCII has a rich history, dating back to its development in the early 1960s. Origi
13 min read
Substring with maximum ASCII sum when some ASCII values are redefined
Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters. Note: Uppercase & lowercase both will be present in the string W. Input: W = "abcde", N = 1,
9 min read
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing/decrementing the ASCII value of any character by 1 any number of times. Note: All characters must be changed to a character of the original string. Examples: Input: S = "geeks"Output: 20Explanation:The minimum number of operations can be attained
6 min read
Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print "-1". Examples: Input:S = ”acd”, T = ”dbf”Output: 1Exp
9 min read
Subsequences generated by including characters or ASCII value of characters of given string
Given a string str of length N, the task is to print all possible non-empty subsequences of the given string such that the subsequences either contain characters or ASCII values of the characters from the given string. Examples: Input: str = "ab" Output: b 98 a ab a98 97 97b 9798 Explanation: Possible subsequence of the strings are { b, a, ab }. Po
6 min read
How To Encode And Decode A Message using Python?
Encryption is the process of converting a normal message (plain text) into a meaningless message (Ciphertext). Whereas, Decryption is the process of converting a meaningless message (Cipher text) into its original form (Plain text). In this article, we will take forward the idea of encryption and decryption and draft a python program. In this artic
3 min read
numpy.defchararray.encode() in Python
numpy.core.defchararray.encode(arr, encoding): This numpy function encodes the string(object) based on the specified codec. Parameters: arr : array-like or string. encoding : [str] Name of encoding being followed. error : Specifying how to handle error. Returns : Encoded string Code: C/C++ Code # Python Program illustrating # numpy.char.encode() me
1 min read
Python | Message Encode-Decode using Tkinter
Prerequisite : Basics of TkinterPython offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Python pr
5 min read
Python | Pandas Series.str.encode()
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.encode() function is used to encode character string in the Series/Index using indicated encoding. Equivalent to str.encode(). Syntax: Series.str.encode(encoding, errors='strict') Parameter : encoding : str errors : str, optional
2 min read
IncrementalEncoder encode() in Python
With the help of IncrementalEncoder.encode() method, we can encode the string into the binary form by using IncrementalEncoder.encode() method. Syntax : IncrementalEncoder.encode(string) Return : Return the encoded string. Note : If you want to use this method you should have python 3.8.2 version or latest. Example #1 : In this example we can see t
1 min read
Python Strings encode() method
Python String encode() converts a string value into a collection of bytes, using an encoding scheme specified by the user. Python String encode() Method Syntax:Syntax: encode(encoding, errors) Parameters: encoding: Specifies the encoding on the basis of which encoding has to be performed. errors: Decides how to handle the errors if they occur, e.g
5 min read
Unicodedata – Unicode Database in Python
Unicode Character Database (UCD) is defined by Unicode Standard Annex #44 which defines the character properties for all unicode characters. This module provides access to UCD and uses the same symbols and names as defined by the Unicode Character Database. Functions defined by the module : unicodedata.lookup(name) This function looks up for the ch
3 min read
How To Convert Unicode To Integers In Python
Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five different methods to achieve this in Python. Convert
2 min read
How To Print Unicode Character In Python?
Unicode characters play a crucial role in handling diverse text and symbols in Python programming. This article will guide you through the process of printing Unicode characters in Python, showcasing five simple and effective methods to enhance your ability to work with a wide range of characters Print Unicode Characters in PythonBelow are the ways
2 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Working with Unicode in Python
Unicode serves as the global standard for character encoding, ensuring uniform text representation across diverse computing environments. Python, a widely used programming language, adopts the Unicode Standard for its strings, facilitating internationalization in software development. This tutorial aims to provide a foundational understanding of wo
3 min read
Convert Unicode String to Dictionary in Python
Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is converting it into a dictionary. In this article, we will
2 min read
Convert Unicode to Bytes in Python
Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations by it. Convert Unicode to Byte in PythonBelow, are
2 min read