Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add option to define delimiter and quoting policy. resolves #10 #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions json_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <node> <json_in_file_path> <csv_out_file_path>\n")
if len(sys.argv) < 4:
print ("\nUsage: python json_to_csv.py <node> <json_in_file_path> <csv_out_file_path> [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()
Expand All @@ -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)
Expand Down