0

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?

3
  • Possible duplicate of Removing u in list Commented Mar 5, 2019 at 8:15
  • What is cjson? Why are you still on an ancient Python version that will be end of life end of this year? Commented Mar 5, 2019 at 8:18
  • 1
    Anyway raw bytes in a Unicode string is never correct, that's not the correct representation. Which bytes are in raw_json? Commented Mar 5, 2019 at 8:19

2 Answers 2

2

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 😊
Sign up to request clarification or add additional context in comments.

Comments

1

Use built-in json module:

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

enter image description here

2 Comments

You are using Python 3, he has this tagged 2 for some reason :-(
Oh, sorry, I didn't notice that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.