Python 如何将dict转储到json文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17043860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dump a dict to a json file?
提问by holys
I have a dict like this:
我有一个这样的字典:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
I can't figure out how to dump the dict to a jsonfile as showed below:
我不知道如何将 dict 转储到json文件中,如下所示:
{
"name": "interpolator",
"children": [
{"name": "ObjectInterpolator", "size": 1629},
{"name": "PointInterpolator", "size": 1675},
{"name": "RectangleInterpolator", "size": 2042}
]
}
Is there a pythonic way to do this?
有没有一种pythonic的方法来做到这一点?
You may guess that I want to generate a d3treemap.
你可能猜到我想生成一个d3树状图。
回答by John La Rooy
This should give you a start
这应该给你一个开始
>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
{
"name": "PointInterpolator",
"size": 1675
},
{
"name": "ObjectInterpolator",
"size": 1629
},
{
"name": "RectangleInterpolator",
"size": 2042
}
]
回答by mgilson
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
当然,顺序不太可能完全保留......但这只是字典的性质......
回答by holys
Combine the answer of @mgilson and @gnibbler, I found what I need was this:
结合@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()
It this way, I got a pretty-print json file.
The tricks print >> f, jis found from here:
http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
通过这种方式,我得到了一个漂亮的 json 文件。技巧print >> f, j是从这里找到的:http:
//www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
回答by moobi
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
This is an easier way to do it.
这是一种更简单的方法。
In the second line of code the file result.jsongets created and opened as the variable fp.
在第二行代码中,文件result.json被创建并作为变量打开fp。
In the third line your dict samplegets written into the result.json!
在第三行中,您的 dictsample被写入result.json!
回答by jmhostalet
with pretty-print format:
使用漂亮的打印格式:
import json
with open(path_to_file, 'w') as file:
json_string = json.dumps(sample, default=lambda o: o.__dict__, sort_keys=True, indent=2)
file.write(json_string)

