merge_json.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #---------------------------------------------------------------------------
3 #
4 # Name: merge_json.py
5 #
6 # Purpose: Merge json files/objects into a single json file/object.
7 #
8 # Created: 3-Apr-2015 H. Greenlee
9 #
10 # Command line usage:
11 #
12 # merge_json.py <jsonfile1> <jsonfile2> ... > out.json
13 #
14 #---------------------------------------------------------------------------
15 
16 from __future__ import absolute_import
17 from __future__ import print_function
18 
19 # Import stuff.
20 
21 import sys, json
22 
23 # Function to merge json objects.
24 # This function assumes that json objects are python dictionaries.
25 
26 def merge_json_objects(json_objects):
27 
28  merged = {}
29 
30  # Loop over input objects and insert all keys into merged object.
31  # It is an error if the same key is encountered twice unless tha values
32  # are identical.
33 
34  for json_object in json_objects:
35  for key in list(json_object.keys()):
36  if key in list(merged.keys()):
37  if json_object[key] != merged[key]:
38  raise RuntimeError('Duplicate nonmatching key %s.' % key)
39  else:
40  merged[key] = json_object[key]
41 
42  # Done.
43 
44  return merged
45 
46 # Function to merge json files and print the result on standard output.
47 
48 def merge_json_files(json_filenames):
49 
50  # Decode all json files into json objects.
51 
52  json_objects = []
53  for json_filename in json_filenames:
54  json_file = open(json_filename)
55  if not json_file:
56  raise IOError('Unable to open json file %s.' % json_filename)
57  obj = json.load(json_file)
58  json_objects.append(obj)
59 
60  # Combine json objects into a single result object.
61 
62  merged = merge_json_objects(json_objects)
63  print(json.dumps(merged, indent=2, sort_keys=True))
64 
65 if __name__ == "__main__":
66 
67  json_filenames = sys.argv[1:]
68  merge_json_files(json_filenames)
69  sys.exit(0)
int open(const char *, int)
Opens a file descriptor.
def merge_json_files(json_filenames)
Definition: merge_json.py:48
def merge_json_objects(json_objects)
Definition: merge_json.py:26