如何将dict转储到json文件?

2024-04-25 10:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的口述:

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

我不知道如何将dict转储到json文件,如下所示:

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

有什么Python的方法可以做到这一点吗?

你可能猜到我想生成一个d3树映射。


Tags: 文件sample方法namejsonsizedictd3
3条回答

结合@mgilson和@gnibbler的回答,我发现我需要的是:


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

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

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

当然,订单不太可能被完全保留。。。但这就是字典的本质。。。

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

这样做比较容易。

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

在第三行,dict sample被写入result.json

相关问题 更多 >