From 2b75c4501951db189b3eb638073a3f8e3ba61480 Mon Sep 17 00:00:00 2001 From: Alexander Leibzon Date: Thu, 31 Oct 2019 20:58:21 +0100 Subject: [PATCH] add option to define delimiter and quoting policy. resolves #10 --- json_to_csv.py | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/json_to_csv.py b/json_to_csv.py index 29a3cf2..a2036c8 100644 --- a/json_to_csv.py +++ b/json_to_csv.py @@ -58,14 +58,34 @@ def reduce_item(key, value): reduced_item[to_string(key)] = to_string(value) +def get_quote_policy(policy): + pol = str(policy).lower() + if pol in ('0', 'minimal'): + return csv.QUOTE_MINIMAL + if pol in ('2','none'): + return csv.QUOTE_NONE + if pol in ('3', 'nonnumeric'): + return csv.QUOTE_NONNUMERIC + + #default behaviour + return csv.QUOTE_ALL + + if __name__ == "__main__": - if len(sys.argv) != 4: - print ("\nUsage: python json_to_csv.py \n") + if len(sys.argv) < 4: + print ("\nUsage: python json_to_csv.py [delimiter] [quote_strategy]\n") else: #Reading arguments node = sys.argv[1] json_file_path = sys.argv[2] csv_file_path = sys.argv[3] + d_delimiter = ',' #default delimiter + q_quote_policy = csv.QUOTE_ALL + + if len(sys.argv)>4: + d_delimiter = sys.argv[4] + if len(sys.argv)>5: + q_quote_policy = get_quote_policy(sys.argv[5]) fp = open(json_file_path, 'r') json_value = fp.read() @@ -91,7 +111,7 @@ def reduce_item(key, value): header.sort() with open(csv_file_path, 'w+') as f: - writer = csv.DictWriter(f, header, quoting=csv.QUOTE_ALL) + writer = csv.DictWriter(f, header, delimiter=d_delimiter, quoting=q_quote_policy) writer.writeheader() for row in processed_data: writer.writerow(row)