简体   繁体   中英

How to decode json unicode string in python?

How can I print decoded_json below so that the emoji appears?

>>> raw_json = '"smile 😊"'
>>> decoded_json = cjson.decode(raw_json)
>>> decoded_json
u'smile \xf0\x9f\x98\x8a'

>>> print decoded_json
smile ð

>>> print 'smile \xf0\x9f\x98\x8a' # u' removed
smile 😊

It seems like cjson.decode returns a u' unicode string. That unicode string has the correct byte representation of the emoji, but when the string is printed some other character appears instead of the emoji. When I print the same string with u' removed, it works.

Is there something I can do to decoded_json so that it will print the emoji?

Add the proper coding on top of your .py files and use the json module.

Python used: (as yours)

$ python --version
Python 2.7.14+

Code:

# -*- coding: utf-8 -*-
import json

raw_json = '"smile 😊"'
decoded_json = json.loads(raw_json)
print decoded_json
print 'smile \xf0\x9f\x98\x8a'

output:

python unicode.py
smile 😊
smile 😊

Use built-in json module:

import json
raw = '{"😊": "smile"}'
print(json.loads(raw))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM