mazieres mazieres - 19 days ago 9
JSON Question

Yet another JSON/encoding error in Python

I've read Unicode HOWTO several times, and solve similar problems many times, still not understanding how. Anyone can help me on how to properly print this loaded json ?

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

import json

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


I've tried every combination of enconding/encode/decode/unicode I could though of... and yet the second print is ugly :

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


Thanks for your help

Answer

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

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

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

print l[0], l[1] is different from print l, so you can always iterate over the elements and print them. print l[0], l[1] will also print the characters properly.

This should help you understand the differences

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>
Comments