Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 #!/usr/bin/python | |
|
qyearsley
2016/07/20 17:57:09
Possibly consider a more specific name for the scr
| |
| 2 # Copyright 2016 The Chromium Authors. All rights reserved. | |
| 3 # Use of this source code is governed by a BSD-style license that can be | |
| 4 # found in the LICENSE file. | |
| 5 | |
| 6 """Converts CSV files to machine-readable JSON. | |
| 7 | |
| 8 Example usage: | |
| 9 | |
| 10 ./csv_to_json input.csv --output directory_owners.json \ | |
| 11 --skip-keys="Number of tests" | |
|
qyearsley
2016/07/20 17:57:09
Could add a backslash at the end of this one (so t
| |
| 12 -f directory number-tests | |
|
qyearsley
2016/07/20 17:57:09
Also add "... team notification-email other-contac
| |
| 13 """ | |
| 14 | |
| 15 import argparse | |
| 16 import csv | |
| 17 import json | |
| 18 import sys | |
| 19 | |
| 20 | |
| 21 def main(argv): | |
| 22 parser = argparse.ArgumentParser() | |
| 23 parser.add_argument('filename', metavar='filename', | |
| 24 help='The path to the input CSV file.') | |
| 25 parser.add_argument('-o', '--output', | |
| 26 help='The output file name.') | |
| 27 parser.add_argument('-f', '--field-names', nargs='*', | |
| 28 help='The ordered field names of the CSV file. Defaults to first row.') | |
| 29 parser.add_argument('-s', '--skip-keys', nargs='*', | |
| 30 help='Fields that should be skipped.') | |
| 31 args = parser.parse_args() | |
| 32 convert_csv_to_json(args.filename, args.output, args.field_names, args.skip_ keys) | |
| 33 | |
| 34 | |
| 35 def convert_csv_to_json(filename, output_filename=None, field_names=None, skip_k eys=None): | |
| 36 out = output_filename or (filename + '.json') | |
| 37 dict_list = [] | |
| 38 json_file = open(out, 'w') | |
| 39 with open(filename) as csv_file: | |
| 40 reader = csv.DictReader(csv_file, fieldnames=field_names) | |
| 41 for row in reader: | |
| 42 if not row['directory'].startswith('imported'): | |
| 43 continue | |
| 44 if skip_keys: | |
| 45 for s in skip_keys: | |
| 46 del row[s] | |
| 47 dict_list.append(row) | |
| 48 json.dump(dict_list, json_file, indent=4) | |
| 49 | |
| 50 | |
| 51 if __name__ == '__main__': | |
| 52 main(sys.argv[1:]) | |
| OLD | NEW |