如何将 dict 转储到 JSON 文件? [英] How to dump a dict to a JSON file?
本文介绍了如何将 dict 转储到 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的字典:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
我不知道如何将 dict 转储到 JSON 文件,如下所示:
I can't figure out how to dump the dict to a JSON file as showed below:
{
"name": "interpolator",
"children": [
{"name": "ObjectInterpolator", "size": 1629},
{"name": "PointInterpolator", "size": 1675},
{"name": "RectangleInterpolator", "size": 2042}
]
}
有没有pythonic的方法来做到这一点?
Is there a pythonic way to do this?
你可能猜到我想生成一个 d3
树状图.
You may guess that I want to generate a d3
treemap.
推荐答案
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
这是一种更简单的方法.
This is an easier way to do it.
在第二行代码中,文件 result.json
被创建并作为变量 fp
打开.
In the second line of code the file result.json
gets created and opened as the variable fp
.
在第三行中,您的字典 sample
被写入 result.json
!
In the third line your dict sample
gets written into the result.json
!
这篇关于如何将 dict 转储到 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文