This repository was archived by the owner on Jan 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge-json
More file actions
executable file
·55 lines (44 loc) · 1.38 KB
/
Copy pathmerge-json
File metadata and controls
executable file
·55 lines (44 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
import json
import sys
import os
from collections import OrderedDict
def print_help():
print("""
Merges all JSON files in the specified directory.
### Usage:
```
$ ./merge-json <directory>
```
E.g. Merge all JSON files in the current directory.
```
$ ./merge-json .
```
The outfile JSON file is saved in the current working directory as `merged.json`.
""")
try:
if len(sys.argv) < 2:
print_help()
else:
input_dir = sys.argv[1]
if not input_dir:
print("No directory specified!")
else:
combined_data = OrderedDict()
count = 1
print("\nFiles to be merged:")
for filename in sorted(os.listdir(input_dir)):
filename = os.path.join(input_dir, filename)
if filename.endswith(".json"):
print(filename)
with open(filename, "r+") as file:
combined_data[f"file_{count}"] = json.load(file)
count += 1
if combined_data:
json.dump(combined_data, fp=open("merged.json", "w"), indent=4)
print(f"\nJSON merge complete! Saved as: ./merged.json\n")
else:
print("\nError! No JSON files found.\n")
except Exception as e:
print(f"Error! Check script comments for usage details!")
print(e, "\n")