0

I am trying to merge two json files in python. Below is my code :

File1.json
{
  "target": {
     "Name": "abc",
     "Occupation": "xyz" 
   },
   "properties":{
      "env" : "dev"
   },
   "use_it": "xyz"
}

File2.json
{
  "pattern": {
     "provider": "abc",
     "schema": "xyz" 
   },
   "baseline":{
      "version" : "dev"
   }      
}





 Code 1 output  :
        {
              "target": {
                 "Name": "abc",
                 "Occupation": "xyz" 
               },
               "properties":{
                  "env" : "dev"
               },
               "use_it": "xyz"
        }
        [
        {
          "pattern": {
             "provider": "abc",
             "schema": "xyz" 
           },
           "baseline":{
              "version" : "dev"
           }      
        }
]

Code 2 Output :
{
          "target": {
             "Name": "abc",
             "Occupation": "xyz" 
           },
           "properties":{
              "env" : "dev"
           },
           "use_it": "xyz"
    }
    ,
    {
      "pattern": {
         "provider": "abc",
         "schema": "xyz" 
       },
       "baseline":{
          "version" : "dev"
       }      
    }
    //Error : cannot parse file1.json // I think because it is not a valid json structure 

Expected output :

{
      "target": {
         "Name": "abc",
         "Occupation": "xyz" 
       },
       "properties":{
          "env" : "dev"
       },
       "use_it": "xyz",
       "pattern": {
         "provider": "abc",
         "schema": "xyz" 
       },
       "baseline":{
          "version" : "dev"
       }   
}

Code 1: 

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

    with open('file1.json', 'a') as output_file:
        json.dump(result, output_file)

Code 2 :
    def merge_JsonFiles(filename):
    f2data = "" 
    
    with open('file2.json') as f2: 
      f2data = '\n' + f2.read()
        
    with open('file1.json','a') as f1:
        f1.write(f2data)


How to achieve Expected output results ?
Bokambo
  • 4,204
  • 27
  • 79
  • 130

0 Answers0