Mercurial > repos > nml > combine_json
comparison combineJSON.py @ 0:116510205617 draft
planemo upload commit dd7f4dc22bbe2f26aafd07a345997db79d9e5ad1
| author | nml |
|---|---|
| date | Wed, 07 Mar 2018 11:39:06 -0500 |
| parents | |
| children | 661bc10b0612 |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:116510205617 |
|---|---|
| 1 #!/usr/bin/env python | |
| 2 import argparse | |
| 3 import json | |
| 4 import sys | |
| 5 | |
| 6 | |
| 7 def init_parser(): | |
| 8 parser = argparse.ArgumentParser( | |
| 9 prog="combineJSON", | |
| 10 formatter_class=argparse.RawDescriptionHelpFormatter, | |
| 11 description="Combine JSON data arrays into a single array") | |
| 12 parser.add_argument('-i', | |
| 13 nargs='*', | |
| 14 help="Input JSON files to be combined") | |
| 15 parser.add_argument('-o', | |
| 16 help='Output file name') | |
| 17 return parser | |
| 18 | |
| 19 | |
| 20 parser = init_parser() | |
| 21 args = parser.parse_args() | |
| 22 input_files = args.i | |
| 23 json_file = [] | |
| 24 | |
| 25 if input_files is None or len(input_files) < 2: | |
| 26 print('Not enough input files. ' | |
| 27 'Please use -i filename.txt filename1.txt ' | |
| 28 'to combine JSON data files') | |
| 29 sys.exit(0) | |
| 30 | |
| 31 | |
| 32 for file_path in input_files: | |
| 33 try: | |
| 34 # Attempt to open each input file, parse as JSON | |
| 35 with open(file_path, 'r') as curr_file: | |
| 36 file_data = curr_file.read() | |
| 37 parsed_json_file = json.loads(file_data) | |
| 38 # Append each valid JSON data array | |
| 39 for entry in parsed_json_file: | |
| 40 json_file.append(entry) | |
| 41 except Exception as e: | |
| 42 print("Help! I can't parse this file {}. " | |
| 43 "Are you sure this is a valid JSON file?" | |
| 44 .format(file_path)) | |
| 45 raise(e) | |
| 46 | |
| 47 if args.o: | |
| 48 with open(args.o, 'w') as out_json: | |
| 49 json.dump(json_file, out_json) | |
| 50 else: | |
| 51 print(json.dumps(json_file)) |
