2010-12-21 108 views
0

我正在閱讀一個JSON字符串,裏面充滿了'串'風格的字符串。例如:如何在Python中將unicode字符串格式化爲utf-8?

[ 
    { 
     "!\/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" 
    } 
    ] 

如果我指定了name = result.name。然後,當我將該值傳遞給一個Django模板時,它顯示爲u'Dominion'

如何將其格式化爲顯示爲Dominion?

++ UPDATE ++

我認爲這個問題有從列表或字典印刷價值的事情。例如:

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) 

此作爲顯示:

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

我需要通過的JSON項目和值的數組來迭代被示出爲具有二進制。爲什麼?

+0

我**強烈**懷疑這是您的實際JSON字符串... – 2010-12-21 00:33:05

+0

整個字符串更長。這是控制檯打印的內容。我沒有想到爲這個問題的目的,有必要張貼原文,但我會更新。 – 2010-12-21 00:34:57

+0

我更感興趣的是您複製值的位置和顯示位置的代碼。 – 2010-12-21 00:38:16

回答

1

games["name"] = name,末尾的逗號使其成爲1元組。去掉它。

+0

我從鍵值對列表中剪切了n,因此是逗號。謝謝! – 2010-12-21 01:48:05

1
>>> # 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 

不知道多少關於Django,但不接受snicode字符串似乎unpythonic給我。

+0

Django *會*取unicodes。這個問題不完整。 – 2010-12-21 00:33:43

0

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