-1

I want to combines all the values for same keys of JSON data using python. Any helping hand would really be appreciated. Please find below the input data:

{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTCOY': 'A'}}}
{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTPFX': 'CN'}}}
{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTNUM': '50003159'}}}

The output format which I want:

{
"MESSAGE_DATA": {
    "BGEN_CENQO_XTRA_KEY": {
        "BGEN_CENQO_CLNTCOY": "A",
        "BGEN_CENQO_CLNTPFX": "CN",
        "BGEN_CENQO_CLNTNUM": "50003159"
    }
}

}

Sourav_Bharadwaj
  • 175
  • 3
  • 11

1 Answers1

0

Slightly changed code from this answer:

from functools import reduce

lst = [{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTCOY': 'A'}}},
{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTPFX': 'CN'}}},
{'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLNTNUM': '50003159'}}}]

def merge(a, b, path=None):
    if path is None: path = []
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            elif a[key] == b[key]:
                pass 
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a

d = reduce(merge, lst)

Structure of dictionary d will be:

{'MESSAGE_DATA': {
    'BGEN_CENQO_XTRA_KEY': {
       'BGEN_CENQO_CLNTCOY': 'A',
       'BGEN_CENQO_CLNTNUM': '50003159',
       'BGEN_CENQO_CLNTPFX': 'CN'
     }
}}
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27