python - 如何用python编写多个json文件?

标签 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"
}

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

最佳答案

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

test_data_list = [test_data, test_data2]

json.dump(test_data_list, json_file)

关于python - 如何用python编写多个json文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56763688/

相关文章:

python Pandas : Find top n and then m in the top n

javascript - 如何使用 JSON 源创建 Mithril.js SPA?

php - Jquery、ajax、json、mysql_query 不起作用

使用 "cp"时的 Python 子进程错误

python - 使用python高效绘制线条

java - 使用 RESTful Jersey 返回自定义 JSON

java - 对象树结构的 JSON 序列化

php - 如何通过 PHP 将从 MySQL 获取的数据编码为 JSON

python - 如何在源代码预览中压缩/删除多个空白行

捕获图像并将其与另一个图像进行比较的python脚本