如何将字典转储到json文件? [英] How to dump a dict to a json file?

查看:161
本文介绍了如何将字典转储到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!

这篇关于如何将字典转储到json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆