【问题标题】:Yet another JSON/encoding error in PythonPython 中的另一个 JSON/编码错误
【发布时间】:2016-11-12 14:35:53
【问题描述】:

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']

感谢您的帮助

【问题讨论】:

    标签: python json unicode encoding utf-8


    【解决方案1】:

    要漂亮地打印您的列表,请尝试以下来自this so question

    print repr(l).decode('unicode-escape')

    此外,当您打印列表时,它会打印元素的repr

    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]
    

    输出

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多