[英]How to append/merge 3 json files into one single json files
我有 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"
}
]
Output 预计单 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'
我知道这是一个需要使用 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
Output:
[
{
"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)
...:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.