hol*_*lys 184 python json dictionary
我有这样的字典:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何将dict转储到json
文件中,如下所示:
{
"name": "interpolator",
"children": [
{"name": "ObjectInterpolator", "size": 1629},
{"name": "PointInterpolator", "size": 1675},
{"name": "RectangleInterpolator", "size": 2042}
]
}
Run Code Online (Sandbox Code Playgroud)
有没有pythonic方式来做到这一点?
您可能猜到我想生成一个d3
树形图.
moo*_*obi 329
import json
with open('result.json', 'w') as fp:
json.dump(sample, fp)
Run Code Online (Sandbox Code Playgroud)
这是一种更简单的方法.
在第二行代码中,文件result.json
被创建并作为变量打开fp
.
在第三行,你的dict sample
被写入result.json
!
hol*_*lys 35
结合@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, j
可以从这里找到:http:
//www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/
als*_*052 23
还想添加这个(Python 3.7)
import json
with open("dict_to_json_textfile.txt", 'w') as fout:
json_dumps_str = json.dumps(a_dictionary, indent=4)
print(json_dumps_str, file=fout)
Run Code Online (Sandbox Code Playgroud)
更新(11-04-2021):所以我添加这个例子的原因是因为有时你可以使用该print()
函数写入文件,这也展示了如何使用缩进(未缩进的东西是邪恶的!!)。然而,我最近开始学习线程,我的一些研究表明该print()
语句并不总是线程安全的。因此,如果您需要线程,您可能需要小心这一点。
mgi*_*son 21
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Run Code Online (Sandbox Code Playgroud)
当然,订单不太可能完全保留......但这只是字典的本质......
Joh*_*ooy 12
这应该给你一个开始
>>> 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
}
]
Run Code Online (Sandbox Code Playgroud)
使用漂亮的打印格式:
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)
Run Code Online (Sandbox Code Playgroud)
如果您正在使用Path
:
Path('result.json').write_text(json.dumps(sample, indent=4) + '\n')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
320804 次 |
最近记录: |