2014-02-13 26 views
0

我試圖將西班牙語單詞的翻譯存儲爲json。但是在python字典和json字符串之間來回轉換的過程正在搞亂我的數據。Python:將字典轉換爲JSON並返回「u」到每個條目

下面的代碼:

import json 

text={"hablar":"reden"} 
print(text)  # {'hablar': 'reden'} 

data=json.dumps(text) 
text=json.loads(data) 

print(text)  # {u'hablar': u'reden} 

爲什麼 「U」 被添加的信?

回答

1

JSON中的字符串被加載到Python中的unicode字符串中。

如果您打印字典,您正在打印repr()其鍵和值的形式。但字符串本身仍然只包含reden

>>> print(repr(text["hablar"])) 
u'reden' 
>>> print(text["hablar"]) 
reden 

一切都應該沒問題。 Unicode是如何處理「人類可讀」字符串的首選方式。 JSON本身不支持二進制數據,因此將JSON字符串解析爲Python unicode是有道理的。

您可以用Python在這裏閱讀更多有關Unicode:http://docs.python.org/2/howto/unicode.html

在Python源代碼,統一文字被寫爲「U」形或「U」爲前綴字符串:u'abcdefghijk'

1

json.loads將字符串讀取爲unicode 。一般來說,這不應該傷害任何東西。

u僅在Unicode對象表示本 - 嘗試print(text['hablar'])沒有u將出席。

+0

很好,謝謝你的快速回答。自從他稍微詳細一點後,他就接受了Messa。 – lhk

0

在U字的意思是這樣的字符串是unicode的,所以你可以使用YAML而不是JSON 這樣的代碼將是:

import yaml 

text={"hablar":"reden"} 
print(text)  # {'hablar': 'reden'} 

data=yaml.dump(text) 
text=yaml.load(data) 

print(text)  # {'hablar': 'reden} 

這個問題有關於YAML更多的細節: What is the difference between YAML and JSON? When to prefer one over the other

+0

如果字典不包含unicode,那麼我不能使用yaml? json會繼續工作嗎? – lhk

+0

您可以在任何情況下使用yaml,如鏈接所示。 –