diff --git a/json_to_csv.py b/json_to_csv.py index 4b7f987..626dd33 100644 --- a/json_to_csv.py +++ b/json_to_csv.py @@ -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)] + return sorted(l, key=alphanum_key) ## # This function converts an item like @@ -87,7 +95,7 @@ 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) @@ -95,4 +103,4 @@ def reduce_item(key, value): for row in processed_data: writer.writerow(row) - print ("Just completed writing csv file with %d columns" % len(header)) \ No newline at end of file + print ("Just completed writing csv file with %d columns" % len(header))