#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Sat Dec 1 10:04:12 2012 @author: bob02 """ import codecs import argparse import json import csv def cmdLineHandler(): """ Command Line Handler @param return: Instance of class argparse.Namespace containing all the parsed command line arguments. """ parser = argparse.ArgumentParser(description="GnuCash Stats for Cristian Marchi", usage='%(prog)s [options] jsonPath csvPath') parser.add_argument('jsonPath', help='Pathname of json file containing stats.') parser.add_argument('csvPath', help='Pathname of csv file to create') args = parser.parse_args() return args """ http://docs.python.org/2/library/csv.html#examples The csv module doesn’t directly support reading and writing Unicode, but it is 8-bit-clean save for some problems with ASCII NUL characters. So you can write functions or classes that handle the encoding and decoding for you as long as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended. """ def doList(l1, value): l2 = [l1] for le1 in value: if isinstance(le1, list): l4 = list() for lex in le1: if isinstance(lex, unicode): lex = lex.encode('utf-8') l4.append(lex) l3 = [None] l3.extend(l4) l2.append(l3) else: l2.append([None, le1.encode('utf-8')]) return l2 def doDict(l1, value, ind): """ Process a Dictionary value @param l1: List containing the key of the value @param value: Dictionary value to process. @param ind: Current dictionary level """ if isinstance(value, dict): keys = value.keys() keys.sort() for k2 in keys: v2 = value[k2] l3 = [None] * ind l3.append(k2.encode('utf-8')) l1.append(l3) l1 = doDict(l1, v2, ind + 1) else: l3 = l1[-1] if isinstance(value, str): value = value.encode('utf-8') l3.append(value) return l1 def main(): """ Function executed when this file is executed. This function is NOT executed when this module is imported. """ args = cmdLineHandler() jsonFD = codecs.open(args.jsonPath, 'r', encoding='UTF-8') try: jsonTree = json.load(jsonFD) except Exception as exception: raise type(exception)('File: {0} - {1}'.format(args.jsonPath, exception.message)) finally: jsonFD.close() csvFD = open(args.csvPath, 'w') csvWriter = csv.writer(csvFD, dialect='excel') keys = jsonTree.keys() keys.sort() for key in keys: value = jsonTree[key] l1 = [[key.encode('utf-8')]] if isinstance(value, list): l1 = doList(l1, value) csvWriter.writerows(l1) elif isinstance(value, dict): l1 = doDict(l1, value, 1) csvWriter.writerows(l1) else: if isinstance(value, unicode): value = value.encode('utf-8') l1.append(value) csvWriter.writerow(l1) csvFD.close() if __name__ == "__main__": main()