简体   繁体   English

将列表的每个元素转储到新行(Python 和 JSON)

[英]Dump each element of list on new line (Python & JSON)

I have a list of dictionaries of the form:我有一个形式的字典列表:

mylist = [{'name': 'Johnny', 'surname': 'Cashew'}, {'name': 'Abraham', 'surname': 'Linfield'}] 

and I am trying to dump that to a json this way:我正在尝试以这种方式将其转储到 json:

with open('myfile.json', 'w') as f:
    json.dump(mylist, f)

but then the entire list is on one line in the json file, making it hardly readable (my list is in reality very long).但是整个列表在 json 文件中的一行上,使其难以阅读(我的列表实际上很长)。 Is there a way to dump each element of my list on a new line?有没有办法将列表中的每个元素转储到新行? I have seen this post that suggests using indent in this way:我看过这篇文章建议以这种方式使用indent

with open('myfile.json', 'w') as f:
    json.dump(mylist, f, indent=2)

but then I get each element within the dictionaries on a new line, like that:但随后我将字典中的每个元素放在一个新行上,如下所示:

[
  {
    'name': 'Johnny',
    'surname: 'Cashew'
  },
  {
    'name': 'Abraham',
    'surname: 'Linfield'
  }
]

whereas what I am hoping to obtain is something like that:而我希望获得的是这样的:

[
  {'name': 'Johnny', 'surname': 'Cashew'},
  {'name': 'Abraham', 'surname': 'Linfield'}
]

Would someone have a hint?有人会有提示吗? Many thanks!非常感谢!

This is a dirty way of doing it but it works for me这是一种肮脏的做法,但它对我有用

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(']')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM