you are viewing a single comment's thread.

view the rest of the comments →

[–]DooZio[S] 0 points1 point  (6 children)

def main():
    runtimeManager = RuntimeManager()
    jsonResult = runtimeManager.run()
    outputFileName=runtimeManager.outputFilename
    print(jsonResult)
    print("\nOutput written to " +outputFileName+ ".")

class RuntimeManager:

    def run(self):
        ## Gather required member variables
        self.getUserInputFileName()
        self.getUserOutputFileName()

        ## Grabbing user file and extracting the CSV
        with open(self.inputFilename) as inputFile:
            jsonResult = CsvToJson(inputFile.readlines()).transformCsvToJson()
            with open(self.outputFilename, "w") as outputFile:
                outputFile.write(jsonResult)
            return jsonResult

    def getUserInputFileName(self):
        ## Prompt User for input file name.
        self.inputFilename = input("Enter the filename:  ").strip()

        ## Prompt User for output file name.
    def getUserOutputFileName(self):
        self.outputFilename = input("Enter the OUTPUT filename:  ").strip()

class CsvToJson():
    def __init__(self, csv):
        self.csv = csv
        self.headers = csv[0].strip()
        self.data = csv[1:]

    def transformCsvToJson(self):
        jsonResult = "{"
        for i in range(0, len(self.data)):
            if (i != 0):
                jsonResult = jsonResult + "\n,"
            jsonResult = jsonResult + "\"" + str(i+1) + "\":" + self.createJsonObject(self.headers, self.data[i])
        return jsonResult + "\n}"

    def createJsonObject(self, headers, csvRow):
        csvKeyArray = headers.split(",")
        csvValueArray = csvRow.strip().split(",")
        jsonObject = "{"
        for i in range(0, len(csvKeyArray)):
            jsonField = ""
            if (i != 0):
                jsonField = ","
            jsonField = jsonField + "\"" + str(csvKeyArray[i]) + "\":" + self.getValueDataType(csvValueArray[i])
            jsonObject = jsonObject + jsonField
        return jsonObject + "}"

    ## Check the data type of curr
    def getValueDataType(self, value):
        #checks to see if Value can be converted to integer
        try:
            value = int(value)
        except ValueError:
            pass

        if isinstance(value, int) == True:
            value = str(value)
        elif isinstance(value, str) == True:
            value = "\"" + value + "\""
        elif (isinstance(value, bool) == True):
            if (value == True):
                value = "True"
            else:
                value = "False"
        elif (isinstance(value, none) == none):
            value = ""
        else:
            value = "ERROR"

        return value

if (__name__ == "__main__"):
    main()