我不确定我是否有这个权利;我想在python中使用json库。
我将嵌套字典转储到磁盘上的json文件中,然后我想像以前一样加载它。虽然当我加载文件时,我没有获得与之前相同的对象。
mydictionary=defaultdict(dict)
...
with open("myfile.json", "w") as outfile:
dump(mydictionary, outfile) #saving the dictionary to json file
....
with open("myfile.json") as outfile:
restored_dict=load(outfile)
for keys in restored_dict:
print keys
字典结构:
{
"product1": {
"item1" : [
"red",
"soft",
"430"
],
"item2" : [
"green",
"soft",
"112"
],
"item3" : [
"blue",
"hard",
"12"
]
},
"product2": {
"item4" : [
"black",
"soft",
"30"
],
"item5" : [
"indigo",
"hard",
"40"
],
"item6" : [
"green",
"soft",
"112"
]
}
}
当我在前后打印物体时,它们不一样;恢复字典后,我无法再访问键和值。我得到一长串数据,每个项目和键的开头都有一个“u”;正确打印它的唯一方法是我再次转储它并打印输出
print dumps(restored_dict, indent=4)
但我仍然无法访问密钥,值和项目。
我看到有两个函数:一个在末尾有s(dump-dumps,load-loads),但我无法区分。网上的一些教程说用s创建一个字符串而不是json对象,而另一些则说用二进制保存,另一个用纯文本保存......
我正在尝试保存字典,并在以后加载它;我认为json是实现这一目标的最简单方法,但由于某种原因我无法实现这一点。
答案 0 :(得分:2)
JSON将数据存储在 Unicode 中。 u
前缀表示您在加载时也有Python字符串。
如果您的密钥只包含ASCII字符,您可以使用字节字符串加载这些密钥(不要使用u
前缀):
>>> import json
>>> d = {'foo': 'bar'}
>>> new_d = json.loads(json.dumps(d))
>>> new_d
{u'foo': u'bar'}
>>> new_d['foo']
u'bar'
如果您的密钥是UTF-8编码的,则必须将这些密钥解码为Unicode字符串,或者使用Unicode字符串文字(再次以u
字符为前缀):
>>> utf8_key = u'å'.encode('utf8') # manually encoded for demo purposes
>>> utf8_key
'\xc3\xa5'
>>> utf8_d = {utf8_key: 'bar'}
>>> utf8_d
{'\xc3\xa5': 'bar'}
>>> new_utf8_d = json.loads(json.dumps(utf8_d))
>>> new_utf8_d
{u'\xe5': u'bar'}
>>> new_utf8_d[u'å']
u'bar'
字符串值仍然是Unicode字符串;如果需要字节,你可以将它们编码回UTF-8,但一般来说最好尽可能地将文本作为Unicode处理。
打印Unicode字符串会将它们自动编码为当前stdout目标的正确编解码器。
您可能想要阅读Python和Unicode:
Ned Batchelder的Pragmatic Unicode presentation
或者,使用pickle
library为您提供往返Python数据格式。然而,输出将不像JSON那样是人类可读的。