如何将字典转储到JSON文件中?

24 浏览
0 Comments

如何将字典转储到JSON文件中?

我有一个像这样的字典:

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

我想知道如何将字典转储为以下显示的JSON文件:

{      
    "name": "interpolator",
    "children": [
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
}

有没有一种pythonic的方法可以做到这一点?

你可能猜到我想产生一个d3树状图。

admin 更改状态以发布 2023年5月20日
0
0 Comments

综合 @mgilson 和 @gnibbler 的答案,我找到了我需要的:

d = {
    "name": "interpolator",
    "children": [{
        'name': key,
        "size": value
        } for key, value in sample.items()]
    }
j = json.dumps(d, indent=4)
with open('sample.json', 'w') as f:
    print >> f, j

这样,我得到了一个漂亮打印的JSON文件。
诀窍print >> f, j 是从这里找到的:
http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

0
0 Comments

import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

这是一种更简单的方法。

在第二行代码中,文件result.json被创建并作为变量fp打开。

在第三行,你的字典sample被写入result.json!

0