Python使用json读取带有表情符号的字符串

时间:2015-03-12 01:34:05

标签: python json facebook emoticons

我有一个巨大的.json文件

我正在阅读

json_data=open('file.json')
data = json.load(json_data)


for item in data['payload']['actions']:
    print item['author']
    print item['action_id']
    print item['body']
json_data.close()

最终其中一个item['body']包含此字符串(实际上是facebook表情符号):

words words stuff stuff\ud83c\udf89\ud83c\udf8a\ud83c\udf87\ud83c\udf86\ud83c\udf08\ud83d\udca5\u2728\ud83d\udcab\ud83d\udc45\ud83d\udeb9\ud83d\udeba\ud83d\udc83\ud83d\ude4c\ud83c\udfc3\ud83d\udc6c

这使得它出现此错误:

Traceback (most recent call last):
  File "curse.py", line 15, in <module>
    print item['body']
  File "C:\python27\lib\encodings\cp437.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 35-63: character maps to <undefined>

有没有办法让它忽略这些?

1 个答案:

答案 0 :(得分:1)

您可以使用string.printable

import string

try:
    print item['body']
except UnicodeEncodeError:
    print(''.join(c for c in item['body'] if c in string.printable))