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

2024-04-20 00:15:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

它是一个对象列表,比如:[ {...}, {...} ... ]?在

其次,我尝试使用python将多个dict存储到单个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'}

以及

^{pr2}$

然后我做了

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文件如下所示

数据.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"
}

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


Tags: 对象namehttpstestcomjsonimgdata