如何从文件夹中打开多个JSON文件,并将它们合并到Python中的单个JSON文件中?

laximzn5  于 2023-02-06  发布在  Python
关注(0)|答案(3)|浏览(206)

假设有3个文件-data1.json、data2.json、data3.json。
假设data1.json包含-

{ 
   "Players":[ 
      { 
         "name":"Alexis Sanchez",
         "club":"Manchester United"
      },
      { 
         "name":"Robin van Persie",
         "club":"Feyenoord"
      }
   ]
}

json包含-

{ 
   "Players":[ 
      { 
         "name":"Nicolas Pepe",
         "club":"Arsenal"
      }
   ]
}

数据3.json包含-

{ 
   "players":[ 
      { 
         "name":"Gonzalo Higuain",
         "club":"Napoli"
      },
      { 
         "name":"Sunil Chettri",
         "club":"Bengaluru FC"
      }
   ]
}

合并这3个文件将生成一个包含以下数据的文件。result.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"
      }
   ]
}

如何从文件夹中打开多个JSON文件,并将它们合并到Python中的单个JSON文件中?

    • 我的方法:**
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)
ttygqcqt

ttygqcqt1#

这可能对你的工作有帮助:

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)
62lalag4

62lalag42#

这正是你想要的

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)

产出

[{"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"}]
iyfamqjs

iyfamqjs3#

上面的两个答案看起来都有效。有人能解释一下为什么使用“二进制”模式来读取文件而不是仅仅阅读它们吗?
使用open(json_file,“rb”)作为输入文件:

相关问题