[英]How to write multiple json files in python?
First of all, I would like to ask what is a typical format of JSON file with multiple objects? 首先,我想问一下带有多个对象的JSON文件的典型格式是什么?
Is it a list of objects like: [ {...}, {...} ... ]
? 它是诸如
[ {...}, {...} ... ]
的对象列表吗?
Second, I tried to store multiple dict
to a single JSON
file using python. 其次,我尝试使用python将多个
dict
存储到单个JSON
文件中。
I have two JSONs: 我有两个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'}
and 和
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'}
then I did 然后我做了
with open('data.json', 'w') as json_file:
json.dump(test_data, json_file, indent=2)
json.dump(test_data2, json_file, indent=2)
Of course, I would have iterated a list of dict
s to store multiple dict
s, but I just did this for now to test if the format is correct. 当然,我会迭代一个
dict
列表来存储多个dict
,但是我现在只是这样做以测试格式是否正确。 The result .json
file looks like 结果
.json
文件看起来像
data.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"
}
It seems pretty weird because there is not ,
between two objects. 这似乎很奇怪,因为没有
,
两个物体之间。 What is the typical way of doing this? 这样做的典型方法是什么?
You need create an object hold all your date in list first.Then dump this list to file. 您需要先创建一个对象,将所有日期保存在列表中。然后将此列表转储到文件中。
test_data_list = [test_data, test_data2]
json.dump(test_data_list, json_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.