[英]How to open multiple JSON file from folder and merge them in single JSON file in python?
Suppose there are 3 files - data1.json, data2.json, data3.json.假设有 3 个文件——data1.json、data2.json、data3.json。
Let's say data1.json contains -假设 data1.json 包含 -
{
"Players":[
{
"name":"Alexis Sanchez",
"club":"Manchester United"
},
{
"name":"Robin van Persie",
"club":"Feyenoord"
}
]
}
data2.json contains - data2.json 包含 -
{
"Players":[
{
"name":"Nicolas Pepe",
"club":"Arsenal"
}
]
}
data3.json contains - data3.json 包含 -
{
"players":[
{
"name":"Gonzalo Higuain",
"club":"Napoli"
},
{
"name":"Sunil Chettri",
"club":"Bengaluru FC"
}
]
}
A merge of these 3 files will generate a file with the following data.这 3 个文件的合并将生成一个包含以下数据的文件。 result.json -
结果.json -
{
"players":[
{
"name":"Alexis Sanchez",
"club":"Manchester United"
},
{
"name":"Robin van Persie",
"club":"Feyenoord"
},
{
"name":"Nicolas Pepe",
"club":"Arsenal"
},
{
"name":"Gonzalo Higuain",
"club":"Napoli"
},
{
"name":"Sunil Chettri",
"club":"Bengaluru FC"
}
]
}
How to open multiple JSON file from folder and merge them in single JSON file in python?如何从文件夹中打开多个 JSON 文件并将它们合并到 python 中的单个 JSON 文件中?
My Approach:我的方法:
import os, json
import pandas as pd
path_to_json = #path for all the files.
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
jsons_data = pd.DataFrame(columns=['name', 'club'])
for index, js in enumerate(json_files):
with open(os.path.join(path_to_json, js)) as json_file:
json_text = json.load(json_file)
name = json_text['strikers'][0]['name']
club = json_text['strikers'][0]['club']
jsons_data.loc[index] = [name, club]
print(jsons_data)
This could to the job for you:这可以为你工作:
import json
import glob
import pprint as pp #Pretty printer
combined = []
for json_file in glob.glob("*.json"): #Assuming that your json files and .py file in the same directory
with open(json_file, "rb") as infile:
combined.append(json.load(infile))
pp.pprint(combined)
This does exactly what you wanted,这正是你想要的,
import json, glob
merged_json = []
for json_file in glob.glob("*json"):
with open(json_file, "rb") as file:
json_data = json.load(file)
if "Players" in json_data:
merged_json += json_data["Players"]
else:
merged_json += json_data["players"]
to_json = json.dumps(merged_json)
print (to_json)
Output Output
[{"name": "Alexis Sanchez", "club": "Manchester United"}, {"name": "Robin van Persie", "club": "Feyenoord"}, {"name": "Nicolas Pepe", "club": "Arsenal"}, {"name": "Gonzalo Higuain", "club": "Napoli"}, {"name": "Sunil Chettri", "club": "Bengaluru FC"}]
Both of the answers above seems like they work.上面的两个答案似乎都有效。 Can someone explain why use the "binary" mode to read the files instead of just reading them?
有人可以解释为什么使用“二进制”模式来读取文件而不是只读取文件吗?
with open(json_file, "rb") as infile:以 open(json_file, "rb") 作为输入文件:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.