codingforfun
codingforfun

Reputation: 31

combining two json to one in python

I am trying to convert multiple json objects to one using python.

example json1: its a huge json with multiple key value pairs but a sample here as an example

[ 
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   }
]

example json 2: its the same format with same key value pair for new set of data

  [ 
       { 
          "key1":"value1",
          "key2":12563
       },
       { 
          "key1":"value1",
          "key2":12563
       }
    ]

I want to combine them so as to get the final result as follow:

[ 
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   }
]

I have tried using json merge library, tried to use json.dumps to serialie and tried and also tried using extend or append functions but not able to get the final result as I want.

Does anyone here have idea on this? Tx.

Upvotes: 0

Views: 51

Answers (1)

user120242
user120242

Reputation: 15268

Regex: \s*\]\s*$

  • \s*: 0 or more whitespaces
  • ]: match on ]
  • $: match on end of string
  • ^: match on beginning of string

Remove ending ] in first json string and [ in second json string and add a , in between to concatenate lists using regex and string replacement:

data1 = """[ 
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   }
]"""
data2 = """
[ 
       { 
          "key1":"value1",
          "key2":12563
       },
       { 
          "key1":"value1",
          "key2":12563
       }
    ]"""

import json, re

result = re.sub(r"\s*\]\s*$",",",data1) + re.sub(r"^\s*\[\s*","",data2)

print(result)

#make sure it's valid json:
json.loads(result)

Deserialize. Append the two lists. Reserialize:

data1 = """[ 
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
      "key1":"value1",
      "key2":12563
   },
   { 
       "key1":"value1",
       "key2":12563
   }
]"""
data2 = """
[ 
       { 
          "key1":"value1",
          "key2":12563
       },
       { 
          "key1":"value1",
          "key2":12563
       }
    ]"""

import json

data1 = json.loads(data1)
data2 = json.loads(data2)

print(json.dumps(data1+data2))

Upvotes: 1

Related Questions