我有一个形式的字典列表。
mylist = [{'name': 'Johnny', 'surname': 'Cashew'}, {'name': 'Abraham', 'surname': 'Linfield'}]
我想用这种方式把它转储到json中去:
with open('myfile.json', 'w') as f:
json.dump(mylist, f)
但在json文件中,整个列表只有一行,这使得它很难读懂(实际上我的列表非常长)。有没有办法把我的列表中的每个元素都转储到新的行上?我看到过 此职位 建议使用 indent
这样一来。
with open('myfile.json', 'w') as f:
json.dump(mylist, f, indent=2)
但是我在字典中的每一个元素都是新的一行,就像这样:
[
{
'name': 'Johnny',
'surname: 'Cashew'
},
{
'name': 'Abraham',
'surname: 'Linfield'
}
]
而我希望得到的是这样的东西。
[
{'name': 'Johnny', 'surname': 'Cashew'},
{'name': 'Abraham', 'surname': 'Linfield'}
]
谁能给点提示?非常感谢!我有一个字典列表。
这是个很脏的方法,但对我来说是有效的。
import json
my_list = [{'name': 'John', 'surname': 'Doe'}, {'name': 'Jane', 'surname': 'Doe'}]
with open('names.json','w') as f:
f.write('[\n')
for d in my_list:
#dumps() instead of dump() so that we can write it like a normal str
f.write(json.dumps(d))
if d == my_list[-1]:
f.write("\n")
break
f.write(",\n")
f.write(']')