Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Python UnicodeEncodeError: 'ascii' codec can't encode characters

There is a json data which contains some Chinese characters.

{
 "font_size": "47",
 "sentences": [
 "你好",
 "sample sentence1",
 "sample sentence2",
 "sample sentence3",
 "sample sentence4",
 "sample sentence5",
 "sample sentence6",
 "sample sentence7",
 "sample sentence8",
 "sample sentence9"
 ]
}

I create a Flask app and use it to receive above json data. I use below curl command to post data.

curl -X POST \
 http://0.0.0.0:5000/ \
 -H 'Cache-Control: no-cache' \
 -H 'Content-Type: application/json;charset=UTF-8' \
 -H 'Postman-Token: af380f7a-42a8-cfbb-9177-74bb348ce5ed' \
 -d '{
 "font_size": "47",
 "sentences": [
 "你好",
 "sample sentence1",
 "sample sentence2",
 "sample sentence3",
 "sample sentence4",
 "sample sentence5",
 "sample sentence6",
 "sample sentence7",
 "sample sentence8",
 "sample sentence9"
 ]
}'

After I receive json data from request.data, I convert it to json, in fact request.data is str.

json_data = json.loads(request.data)

Then I want to format a string with json_data.

subtitles.format(**json_data)

I got an error.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

How to solve it? Thanks in advance.

EDIT

subtitles is read from file.

subtitles_file = "{path}/templates/sorry/subtitles.ass".format(path=root_path)
with open(subtitles_file, 'r') as file:
 subtitles = file.read()

EDIT Python 2 or Python 3

I'm using python 2 and this error occurs. However Python 3 can automatically handle this. So enjoy Python 3.

Answer*

Draft saved
Draft discarded
Cancel
1
  • Very nice answer. Thanks a lot. Commented Mar 14, 2018 at 6:57

lang-py

AltStyle によって変換されたページ (->オリジナル) /