【问题标题】:Dump each element of list on new line (Python & JSON)将列表的每个元素转储到新行(Python 和 JSON)
【发布时间】:2020-08-29 18:34:22
【问题描述】:

我有一个表格的字典列表:

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

我正在尝试以这种方式将其转储到 json:

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

但是整个列表在 json 文件的一行中,使其难以阅读(我的列表实际上很长)。有没有办法将列表中的每个元素转储到新行?我看到this post 建议以这种方式使用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'}
]

有人有提示吗?非常感谢!

【问题讨论】:

  • 这是内置 JSON 库允许的唯一缩进配置。

标签: python json list dictionary dump


【解决方案1】:

这是一种肮脏的做法,但它对我有用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多