简体   繁体   中英

How to format unicode strings to utf-8 in Python?

I'm reading in a JSON string which is littered with u'string' style strings. Example:

 [
     {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        }, 
        "year": {
          "value": "1996"
        }
      }, 
      "guid": "#9202a8c04000641f80000000003a0ee6", 
      "type": "\/games\/game", 
      "id": "\/en\/el_grande", 
      "name": "El Grande"
    }, 
    {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        }, 
        "year": {
          "value": "1995"
        }
      }, 
      "guid": "#9202a8c04000641f80000000000495ec", 
      "type": "\/games\/game", 
      "id": "\/en\/settlers_of_catan", 
      "name": "Settlers of Catan"
    }
  ]

If I assign name = result.name. Then when I log of pass that value to a Django template, it displays as u'Dominion'

How do I format it to display as Dominion?

++ UPDATE ++

I think the problem has to do with printing values from a list or dictionary. For example:

result = freebase.mqlread(query)

games = {}
count = 0
r = result[0]
name = r.name
games["name"] = name,
self.response.out.write(games["name"])
self.response.out.write(name)

This displays as:

(u'Dominion',)  // saved response to dictionary, and then printed
Dominion        // when calling the value directly from the response

I need to iterate through an array of JSON items and the values are being shown with the unicode. Why?

>>> # example
>>> s = u"Jägermütze"
>>> s.encode("utf-8")
'J\xc3\xa4germ\xc3\xbctze'
>>> print s.encode("utf-8") # on a utf-8 terminal
Jägermütze

Don't know much about Django, but not accepting snicode strings seems unpythonic to me.

The comma at the end of games["name"] = name, makes it a 1-tuple. Remove it.

您可以使用str(your string)执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM