如何将字典转储到json文件?

问题描述:

我有一个这样的字典:

sample = {'ObjectInterpolator': 1629,  'PointInterpolator': 1675, 'RectangleInterpolator': 2042}

我不知道如何将字典转储到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}
     ]
}

是否有Python方式可以做到这一点?

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!