如何将python字典保存到json文件中?

Mic*_*ael 2 python json dictionary

我有一本字典,例如:

a = {'a':1,'b':2,'c':3}
Run Code Online (Sandbox Code Playgroud)

我希望它保存在一个 json 文件中。

我如何使用原始的 python json 库来做到这一点?

请注意,我正在运行 Python 3.5.2,它有一个内置的 json 库。

abc*_*ccd 5

您也可以直接使用json.dump代替.dump 转储 json 文件json.dumps

import json
a = {'a':1,'b':2,'c':3}
with open("your_json_file", "w") as fp:
    json.dump(a , fp) 
Run Code Online (Sandbox Code Playgroud)

json.dumps主要用于将字典显示为字符串类型的json格式。而转储用于保存到文件。使用它来保存到文件已过时。

前面的示例仅将文件保存为 json,但并没有使它变得非常漂亮。所以你可以这样做:

json.dump(a, fp, indent = 4) # you can also do sort_keys=True as well
# this work the same for json.dumps
Run Code Online (Sandbox Code Playgroud)

这使得 json 文件更易于用户阅读。pydoc对如何使用 json 模块有一些很好的描述。

要取回您的数据,您可以使用该load功能。

a = json.load(fp) # load back the original dictionary
Run Code Online (Sandbox Code Playgroud)


Ash*_*lam 4

这可能会帮助你...

import json
a = {'name': 'John Doe', 'age': 24}
js = json.dumps(a)

# Open new json file if not exist it will create
fp = open('test.json', 'a')

# write to json file
fp.write(js)

# close the connection
fp.close()
Run Code Online (Sandbox Code Playgroud)