Python dump dict到json文件 [英] Python dump dict to json file
本文介绍了Python dump dict到json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
sample = {'ObjectInterpolator':1629,'PointInterpolator':1675,' RectangleInterpolator':2042}
我无法弄清楚如何将dict转储为 json
文件如下所示:
{
name: interpolator,
children:[
{name:ObjectInterpolator,size:1629},
{name:PointInterpolator,size },
{name:RectangleInterpolator,size:2042}
]
}
有没有pythonic的方式来做到这一点?
您可能会猜到我想生成一个 d3
treemap。
解决方案
import json
with open('result.json','w')as fp:
json.dump(sample,fp)
这是一个更简单的方法。
在第二行代码中,文件 result.json
被创建并打开为变量 fp
。
在第三行,您的dict 样本
被写入 result.json
!
I have a dict like this:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
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}
]
}
Is there a pythonic way to do this?
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.
In the second line of code the file result.json
gets created and opened as the variable fp
.
In the third line your dict sample
gets written into the result.json
!
这篇关于Python dump dict到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文