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

2024-05-15 01:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有3个文件-data1.json、data2.json、data3.json。你知道吗

假设data1.json包含-

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

data2.json包含-

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

data3.json包含-

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

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

如何在python中打开文件夹中的多个JSON文件并将它们合并到单个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)

Tags: 文件topathtextnameposjsonfor
2条回答

这可能会影响到你的工作:

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)

这正是你想要的

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"}]

相关问题 更多 >

    热门问题