我有一个这样的字典:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
我不知道如何将 dict 转储到 JSON 文件,如下所示:
{
"name": "interpolator",
"children": [
{"name": "ObjectInterpolator", "size": 1629},
{"name": "PointInterpolator", "size": 1675},
{"name": "RectangleInterpolator", "size": 2042}
]
}
有没有pythonic方法可以做到这一点?
你可能猜到我想生成一个d3
树形图。
最佳答案
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
这是一种更简单的方法。
在第二行代码中,文件 result.json
被创建并作为变量 fp
打开。
在第三行中,您的字典 sample
被写入 result.json
!
https://stackoverflow.com/questions/17043860/
相关文章:
javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr
java - 在 Java 中将 XML 转换为 JSON 的最快方法
python - 为什么我看到 "TypeError: string indices must be
jquery - 为什么每个人都为 jQuery 选择 JSON 而不是 XML?
javascript - JSON 省略了 Infinity 和 NaN; ECMAScript 中
c# - 如何将 C# 匿名类型序列化为 JSON 字符串?