Python 如何在JSON文件中编写字典列表

Python 如何在JSON文件中编写字典列表,python,json,Python,Json,我试图在JSON文件中编写字典列表,但我遇到了困难,这导致为每个dict创建列表,并且在每个dict之后都缺少逗号 到目前为止,我尝试的是: data_list = [data] with open('data.json', 'a') as out_file: json.dump([data.__dict__ for data in data_list], out_file) 结果我得到: [ { "id": "1", &q

我试图在JSON文件中编写字典列表,但我遇到了困难,这导致为每个dict创建列表,并且在每个dict之后都缺少逗号

到目前为止,我尝试的是:

data_list = [data]

with open('data.json', 'a') as out_file:
    json.dump([data.__dict__ for data in data_list], out_file)
结果我得到:

[
  {
    "id": "1",
    "task_id": "task_1",
    "link": "https://google.com",
    "title": "Google",
    "message": "Redirect",
    "hits": 0
  }
][
  {
    "id": "2",
    "task_id": "task_2",
    "link": "https://fb.com",
    "title": "Facebook",
    "message": "Redirect",
    "hits": 0
  }
]
这是JSON文件中的预期行为:

[
  {
    "id": "1",
    "task_id": "task_1",
    "link": "https://google.com",
    "title": "Google",
    "message": "Redirect",
    "hits": 0
  },

  {
    "id": "2",
    "task_id": "task_2",
    "link": "https://fb.com",
    "title": "Facebook",
    "message": "Redirect",
    "hits": 1
  }
]

还尝试了
json.dumps()
,它没有返回任何内容。

您可以发布示例输入吗请添加您的输入
字典
数据列表是什么样子的?它看起来像是在附加到一个文件,因此每次写入该文件时,您都会得到一个新数组。您不能期望该文件是智能的并合并阵列,您必须自己这样做。如果您需要将内容附加到以前存在的数组中,yoiu必须加载以前存在的数组,附加新字典,然后用整个数组重写文件。
data
dict看起来像我得到的结果,但没有列表括号。因此,我将dict添加到列表中,然后尝试将其转储到json中。