0

I have 3 json files with differen key pair values and all files reside in same directory. I need to merge/append all 3 json into single json file which will be used to some frontend application usage

Example files I have:

File 1:

[
    {
        "Key": "Region",
        "Value": "US"
    },
    {
        "Key": "Zone",
        "Value": "1"
    }
]

File 2:

[
    {
        "Drive": "/dev/sdb",
        "Size(GB)": "20",
        "Encrypted": true
    }
]

File 3:

[
    {
        "AlarmName": "Test",
        "StateValue": "OK"
    }
]

Output expected single json:

[
    {
        "Key": "Region",
        "Value": "US"
    },
    {
        "Key": "Zone",
        "Value": "1"
    },
    {
        "Drive": "/dev/sdb",
        "Size(GB)": "20",
        "Encrypted": true
    },
    {
        "AlarmName": "Test",
        "StateValue": "OK"
    }
]

can some one suggest or any reference specific reference for this

EDIT 1:

Tried some suggestion in python below:

import json

f1data = f2data = f3data = "" 
 
with open(f'C:\csv\file1.json') as f1: 
  f1data = f1.read() 

with open(f'C:\csv\file2.json') as f2: 
  f2data = f2.read()

with open(f'C:\csv\file3.json') as f3: 
  f3data = f3.read()   
 


 f1data += "\n"
f1data += f2data
f2data += f3data

with open ('C:\csv\combined.json', 'w') as f3: 
  f4.write(f1data)

its erroring out

OSError: [Errno 22] Invalid argument: 'C:\\csv\file3.json'
asp
  • 777
  • 3
  • 14
  • 33

1 Answers1

1

I know this is a question needs to use python, but thought of sharing my experience using bash. You can easily do this using bash.

a.json

[
  {
      "Key": "Region",
      "Value": "US"
  },
  {
      "Key": "Zone",
      "Value": "1"
  }
]

b.json

[
    {
        "Drive": "/dev/sdb",
        "Size(GB)": "20",
        "Encrypted": true
    }
]

c.json

[
    {
        "AlarmName": "Test",
        "StateValue": "OK"
    }
]

Using jq command line utility, you can easily combine the files.

jq -s '[.[][]]' a.json b.json c.json

Output:

[
  {
    "Key": "Region",
    "Value": "US"
  },
  {
    "Key": "Zone",
    "Value": "1"
  },
  {
    "Drive": "/dev/sdb",
    "Size(GB)": "20",
    "Encrypted": true
  },
  {
    "AlarmName": "Test",
    "StateValue": "OK"
  }
]

In python:

Note: The following code works if the json files have json array data

In [10]: import json, glob

In [11]: data = []

In [12]: for f in glob.glob("*.json"):
    ...:     with open(f) as fp:
    ...:         data.extend(json.load(fp))
    ...:

In [13]: data
Out[13]:
[{'Key': 'Region', 'Value': 'US'},
 {'Key': 'Zone', 'Value': '1'},
 {'AlarmName': 'Test', 'StateValue': 'OK'},
 {'Drive': '/dev/sdb', 'Size(GB)': '20', 'Encrypted': True}]

In [14]: with open("combined.json","w") as f:
    ...:     json.dump(data,f)
    ...:
bigbounty
  • 16,526
  • 5
  • 37
  • 65