2013-05-14 69 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'}