我正在编写一个程序,将数据存储在字典对象中,但此数据需要在程序执行期间的某个点保存,并在程序再次运行时加载回字典对象。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。


当前回答

在中文中,你应该做以下调整:

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')

其他回答

如果你关心速度,可以使用ujson (UltraJSON),它有和json相同的API:

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

我使用yaml,如果需要可读(既不是JSON也不是XML, IMHO),或者如果阅读是不必要的,我使用pickle。

from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)

读回

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

json模块是一个很好的解决方案。与pickle相比,它的优点是只生成纯文本输出,并且是跨平台和跨版本的。

import json
json.dumps(dict)

我使用json:

import json

# convert to string
input_ = json.dumps({'id': id_ })
    
# load to dict
my_dict = json.loads(input_) 

在中文中,你应该做以下调整:

import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')