首先我想问一下,多对象的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/