[英]How to write multiple json files in python?
首先,我想问一下带有多个对象的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.