Skip to content

Added a natural method of sorting #27

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

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
12 changes: 10 additions & 2 deletions json_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ def to_string(s):
#Change the encoding type if needed
return s.encode('utf-8')

def sorted_nicely(l):
"""
Sort the given iterable in the way that humans expect.
https://stackoverflow.com/a/2669120
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing import re for regular expressions.

return sorted(l, key=alphanum_key)

##
# This function converts an item like
Expand Down Expand Up @@ -87,12 +95,12 @@ def reduce_item(key, value):
processed_data.append(reduced_item)

header = list(set(header))
header.sort()
header = sorted_nicely(header)

with open(csv_file_path, 'w+') as f:
writer = csv.DictWriter(f, header, quoting=csv.QUOTE_ALL)
writer.writeheader()
for row in processed_data:
writer.writerow(row)

print ("Just completed writing csv file with %d columns" % len(header))
print ("Just completed writing csv file with %d columns" % len(header))