python - Python 中的另一个 JSON/编码错误

标签 python json unicode encoding utf-8

我已阅读 Unicode HOWTO好几次了,解决了好多次类似的问题,还是不明白怎么办。任何人都可以帮助我如何正确打印此加载的 json ?

#!/usr/bin/env python2
# coding: utf8

import json

s = u'["poêle", "mangé"]'
print s
l = json.loads(s)
print l

我已经尝试了我能想到的所有编码/编码/解码/unicode组合...但第二个打印很丑陋:

$ python test.py
["poêle", "mangé"]
[u'po\xeale', u'mang\xe9']

感谢您的帮助

最佳答案

To pretty print your list try the following taken from this so question

打印repr(l).decode('unicode-escape')

Also, when you print a list, it prints the repr of the elements.

print l[0], l[1]print l 不同,因此您始终可以迭代元素并打印它们。 print l[0], l[1] 也将正确打印字符。

这应该可以帮助您理解差异

class MyClass(object):
    def __repr__(self):
        return "<repr: MyClass>"

    def __str__(self):
        return "<str: MyClass>"

l = [ MyClass(), MyClass(), MyClass() ]
print l
print l[0], l[1], l[2]

output

[<repr: MyClass>, <repr: MyClass>, <repr: MyClass>]
<str: MyClass> <str: MyClass> <str: MyClass>

关于python - Python 中的另一个 JSON/编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40563884/

相关文章:

将主机字符编码中的字符串转换为 C 中的 Unicode

python - 在 python 中使用 lambda 函数创建差异数组

python - 在 GAE 的 Python 中将实体键序列化为字符串

javascript - 使用列名获取存储值 - EXTJS 4

php - 使用 httpclient 从 webservice 读取

c++ - en_US.UTF-8 区域设置的 Windows 等效项是什么?

python - 用于 Python 中的网页抓取的 Newspaper 0.0.6

python - 解压文件导致 "BadZipFile: File is not a zip file"

iphone - 没有根元素 ios 的 Json

unicode - 相同的 Unicode 字符有时显示为纯黑色,有时显示为彩色图标