davidb
davidb

Reputation: 1603

Python3 json with japanese characters

I am using aws lambda to return a simple json with some Japanese characters. I can't seem to get the characters to display correctly. Here's what my code looks like:

def lambda_handler(event, context):

minutes = datetime.datetime.now().minute
status = ""

if minutes < 10:
    status = u"良好"
else:
    status = u"不良"

response = {}
response['ID'] = 1
response['Status'] = status

data = json.dumps(response, indent=2, ensure_ascii=False)
data = json.loads(data)

return data

The above code returns:

{"ID": 1, "Status": "\u4e0d\u826f"}

I have also tried this:

data = json.dumps(response, indent=2, ensure_ascii=False).encode('utf-8)

But to no avail.

How can I get the response to return japanese characters?

Edit: One more thing I noticed. In the browser I get the above json output, however when running a test in AWS console I get the characters displayed properly. What does this mean?

Upvotes: 2

Views: 1073

Answers (2)

user3821178
user3821178

Reputation: 373

In case you are running flask using the ensure_ascii did not fix the problem, you have to change disable it on the app level this way:

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

Upvotes: 0

hata
hata

Reputation: 12478

Isn't it your terminal's problem?

I got Japanese characters displayed correctly on my Mac terminal.

import json

minutes = 9
status = ""

if minutes < 10:
    status = u"良好"
else:
    status = u"不良"

response = {}
response['ID'] = 1
response['Status'] = status

data = json.dumps(response, indent=2, ensure_ascii=False)
data = json.loads(data)

print(data)

{'ID': 1, 'Status': '良好'}

https://ideone.com/XZeVkS

Upvotes: 2

Related Questions