如何在python中写入多个json文件?

时间:2019-06-26 00:39:04

标签: python json

首先,我想问一下带有多个对象的JSON文件的典型格式是什么?

它是像[ {...}, {...} ... ]这样的对象的列表吗?

第二,我尝试使用python将多个dict存储到单个JSON文件中。

我有两个JSON:

test_data = {'profile_img': 'https://fmdataba.com/images/p/4592.png',
 'name': 'Son Heung-Min ',
 'birth_date': '8/7/1992',
 'nation': 'South Korea KOR',
 'position': 'M (R), AM (RL), ST (C)',
 'foot': 'Either'}

test_data2 = {'profile_img': 'https://fmdataba.com/images/p/1103.png',
 'name': 'Marc-André ter Stegen ',
 'birth_date': '30/4/1992',
 'nation': 'Germany',
 'position': 'GK',
 'foot': 'Either'}

然后我做了

with open('data.json', 'w') as json_file:  
    json.dump(test_data, json_file, indent=2)
    json.dump(test_data2, json_file, indent=2)

当然,我会迭代dict的列表来存储多个dict,但是我现在只是这样做以测试格式是否正确。结果.json文件看起来像

data.json

{
  "profile_img": "https://fmdataba.com/images/p/4592.png",
  "name": "Son Heung-Min ",
  "birth_date": "8/7/1992",
  "nation": "South Korea KOR",
  "position": "M (R), AM (RL), ST (C)",
  "foot": "Either"
}{
  "profile_img": "https://fmdataba.com/images/p/1103.png",
  "name": "Marc-Andr\u00e9 ter Stegen ",
  "birth_date": "30/4/1992",
  "nation": "Germany",
  "position": "GK",
  "foot": "Either"
}

看起来很奇怪,因为两个对象之间没有,。 这样做的典型方法是什么?

1 个答案:

答案 0 :(得分:0)

您需要先创建一个对象,将所有日期保存在列表中。然后将此列表转储到文件中。

test_data_list = [test_data, test_data2]

json.dump(test_data_list, json_file)