|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Copyright 2021 Nigel Small |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | + |
| 19 | +from csv import reader |
| 20 | +from json import dumps as json_dumps |
| 21 | + |
| 22 | +from escli.commands import Command |
| 23 | + |
| 24 | + |
| 25 | +class JsonifyCommand(Command): |
| 26 | + """ Convert input data to JSON documents. |
| 27 | + """ |
| 28 | + |
| 29 | + def get_name(self): |
| 30 | + return "jsonify" |
| 31 | + |
| 32 | + def get_description(self): |
| 33 | + return self.__doc__.strip() |
| 34 | + |
| 35 | + def register(self, subparsers): |
| 36 | + parser = subparsers.add_parser(self.get_name(), description=self.get_description()) |
| 37 | + parser.add_argument("file", metavar="FILE", |
| 38 | + help="Filename from which to load data.") |
| 39 | + parser.add_argument("-i", "--include", default="*", |
| 40 | + help="Fields to include (comma-separated list).") |
| 41 | + parser.set_defaults(f=self.jsonify) |
| 42 | + return parser |
| 43 | + |
| 44 | + def jsonify(self, args): |
| 45 | + """ Convert input data to JSON documents. |
| 46 | + """ |
| 47 | + with open(args.file, newline="") as csv_file: |
| 48 | + csv_reader = reader(csv_file) |
| 49 | + keys = None |
| 50 | + for line_no, line in enumerate(csv_reader): |
| 51 | + if line_no == 0: |
| 52 | + keys = line |
| 53 | + if args.include == "" or args.include == "*": |
| 54 | + include_keys = None |
| 55 | + else: |
| 56 | + include_keys = args.include.split(",") |
| 57 | + else: |
| 58 | + values = list(map(simplify_type, line)) |
| 59 | + data = dict(zip(keys, values)) |
| 60 | + if include_keys: |
| 61 | + data = dict(zip(include_keys, [data[k] for k in include_keys])) |
| 62 | + print(json_dumps(data)) |
| 63 | + |
| 64 | + |
| 65 | +def simplify_type(value): |
| 66 | + try: |
| 67 | + int_value = int(value) |
| 68 | + except ValueError: |
| 69 | + try: |
| 70 | + float_value = float(value) |
| 71 | + except ValueError: |
| 72 | + return value |
| 73 | + else: |
| 74 | + return float_value |
| 75 | + else: |
| 76 | + return int_value |
0 commit comments