2013-05-14 66 views
0

當我保存JSON一切都在文件好的,但是當我負載加載的對象是不正確的。JSON負荷是不正確的(蟒蛇)

file=open("hello", "w") 

a={'name':'jason', 'age':73, 'grade':{ 'computers':97, 'physics':95, 'math':89} } 

json.dump(a, file) 

正如我在文件中說的那樣沒問題,但是當我加載的時候你可以看到一個問題。

文件:

" {"age": 73, "grade": {"computers": 97, "physics": 95, "math": 89}, "name": "jason"} " 

現在負載:

b=json.load(file) 

print b 

輸出:

{u"age": 73, u"grade": {u"computers": 97, u"physics": 95, u"math": 89}, u"name": u"jason"}

你可以清楚地發現,每一個字符串之前有ü。它不影響代碼,但我不喜歡它..

爲什麼會發生這種情況?

+3

它只是將其保存爲Unicode。 – karthikr 2013-05-14 16:28:28

+0

http://docs.python.org/2/howto/unicode.html – root 2013-05-14 16:28:36

回答

1

它只是在表示...它不是真的有它只是表示它是unicode

print u"this" == "this" 

不知道這需要其自己的答案:/

+0

我知道,有沒有辦法刪除它? – 2013-05-14 16:38:36

+0

我假設你沒有運行python 3.X.我相當肯定,如果你用python 3.x解釋器運行它,你將不會看到unicode'u'...我想你可以用ascii編碼並使用str()? – jheld 2013-05-14 16:43:56

+0

@Ofek .T .:你爲什麼要改變一個字符串的_representation_?如果你只是打印數據一切都很好。 – Matthias 2013-05-14 18:26:16

0

這裏是Unicode的轉換功能字典到UTF8字典。

def uni2str(input): 
    if isinstance(input, unicode): 
     return input.encode('utf-8') 
    elif isinstance(input, dict): 
     return {uni2str(key): uni2str(value) for key, value in input.items()} 
    elif isinstance(input, list): 
     return [uni2str(element) for element in input] 
    else: 
     return input 

a = {u'name':u'Yarkee', u'age':23, u'hobby':[u'reading', u'biking']} 

print(uni2str(a)) 

輸出將是:

{'hobby': ['reading', 'biking'], 'age': 23, 'name': 'Yarkee'}