我有一本字典,例如:
a = {'a':1,'b':2,'c':3}
我希望将它保存在一个 json 文件中。
如何使用原始的 python json 库执行此操作?
请注意,我正在运行 Python 3.5.2,它有一个内置的 json 库。
请您参考如下方法:
您也可以使用 json.dump 代替 json.dumps 直接转储 json 文件。
import json
a = {'a':1,'b':2,'c':3}
with open("your_json_file", "w") as fp:
json.dump(a , fp)
json.dumps主要用于将字典显示为json格式,类型为string。而转储用于保存到文件。使用它保存到文件已过时。
前面的例子只是将文件保存为json,并没有做的很漂亮。所以你可以这样做:
json.dump(a, fp, indent = 4) # you can also do sort_keys=True as well
# this work the same for json.dumps
这使得 json 文件更易于阅读。 the pydoc 对如何使用 json 模块有一些很好的描述。
要取回您的数据,您可以使用load 函数。
a = json.load(fp) # load back the original dictionary
