Chromium Code Reviews| Index: third_party/WebKit/Tools/Scripts/csv_to_json |
| diff --git a/third_party/WebKit/Tools/Scripts/csv_to_json b/third_party/WebKit/Tools/Scripts/csv_to_json |
| new file mode 100755 |
| index 0000000000000000000000000000000000000000..a17d195680e81fb78cd3e1ecded51b11d7d61136 |
| --- /dev/null |
| +++ b/third_party/WebKit/Tools/Scripts/csv_to_json |
| @@ -0,0 +1,43 @@ |
| +#!/usr/bin/python |
| +# Copyright 2016 The Chromium Authors. All rights reserved. |
| +# Use of this source code is governed by a BSD-style license that can be |
| +# found in the LICENSE file. |
| + |
| +"""Converts CSV files to machine-readable JSON.""" |
|
qyearsley
2016/07/19 22:17:28
I think it would be helpful give an example invoca
|
| + |
| +import argparse |
| +import csv |
| +import json |
| +import sys |
| + |
| + |
| +def main(argv): |
| + parser = argparse.ArgumentParser() |
| + parser.add_argument('filename', metavar='filename', |
| + help='The path to the input CSV file.') |
| + parser.add_argument('-o', '--output', |
| + help='The output file name.') |
| + parser.add_argument('-f', '--fieldnames', nargs='*', |
|
qyearsley
2016/07/19 22:17:28
fieldnames -> field-names?
|
| + help='The ordered fieldnames of the CSV file. Defaults to first row.') |
|
qyearsley
2016/07/19 22:17:28
fieldnames -> field names
|
| + parser.add_argument('-s', '--skip-keys', nargs='*', |
| + help='Fields that should be skipped.') |
| + args = parser.parse_args() |
| + convert_csv_to_json(args.filename, args.output, args.fieldnames, args.skip_keys) |
| + |
| + |
| +def convert_csv_to_json(filename, output_filename=None, field_names=None, skip_keys=None): |
| + out = output_filename or (filename + '.json') |
| + dict_list = [] |
| + json_file = open(out, 'w') |
| + with open(filename) as csv_file: |
| + reader = csv.DictReader(csv_file, fieldnames=field_names) |
|
qyearsley
2016/07/19 22:17:28
fieldnames -> field_names
|
| + for row in reader: |
| + if skip_keys: |
| + for s in skip_keys: |
| + del row[s] |
| + dict_list.append(row) |
| + json.dump(dict_list, json_file, indent=4) |
| + |
| + |
| +if __name__ == '__main__': |
| + main(sys.argv[1:]) |
|
qyearsley
2016/07/19 22:17:28
four-space indent
|