如何将3个json文件附加/合并到一个json文件中

时间:2020-07-21 07:00:57

标签: python json merge

我有3个具有不同密钥对值的json文件,所有文件都位于同一目录中。我需要将所有3个json合并/附加到单个json文件中,这将用于一些前端应用程序使用

我拥有的示例文件:

文件1:

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

文件2:

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

文件3:

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

输出预期的单个json:

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

有人可以为此建议或任何参考特定的参考

编辑1:

在下面的python中尝试了一些建议:

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)

错误提示

OSError: [Errno 22] Invalid argument: 'C:\\csv\file3.json'

1 个答案:

答案 0 :(得分:1)

我知道这是使用python需要解决的一个问题,但想到了使用bash分享我的经验。您可以使用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"
    }
]

使用jq命令行实用工具,可以轻松地合并文件。

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

输出:

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

在python中:

注意:如果json文件具有json数组数据,则以下代码有效

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)
    ...: