Python >> Tutoriel Python >  >> Python Tag >> JSON

Comment fusionner plusieurs fichiers json en un seul fichier en python

Vous devez utiliser extend au lieu de append . Il ajoutera les éléments de la liste transmise à result au lieu d'une nouvelle liste :

files=['my.json','files.json',...,'name.json']

def merge_JsonFiles(filename):
    result = list()
    for f1 in filename:
        with open(f1, 'r') as infile:
            result.extend(json.load(infile))

    with open('counseling3.json', 'w') as output_file:
        json.dump(result, output_file)

merge_JsonFiles(files)

import json
import pandas as pd

with open('example1.json') as f1:               # open the file
    data1 = json.load(f1)

with open('example2.json') as f2:                # open the file       
    data2 = json.load(f2)
    
df1 = pd.DataFrame([data1])                      # Creating DataFrames
df2 = pd.DataFrame([data2])                      # Creating DataFrames

MergeJson = pd.concat([df1, df2], axis=1)         # Concat DataFrames

MergeJson.to_json("MergeJsonDemo.json")          # Writing Json