Python手动CSV转JSON:数值类型错误添加引号问题求助
问题:CSV转JSON时整数被错误添加引号
我正在完成编程逻辑入门课程的作业,需从.txt文件读取CSV格式数据,手动转换为JSON格式后写入新.txt文件并打印到屏幕。作业要求不能使用Python内置JSON模块,但目前遇到问题:整数(如Program Code的3504)等无需引号的数据类型被错误添加了引号。
代码实现
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 self.inputFilename = input("Enter the filename: ").strip() 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 + "}" def getValueDataType(self, value): if (type(value) == int): value = str(value) elif (type(value) == str): value = "\"" + value + "\"" elif (type(value) == bool): if (value): value = "true" else: value = "false" elif (type(value) == null): value = "null" else: value = "ERROR" return value if (__name__ == "__main__"): main()
错误输出
{"1":{"Last Name":"Minion","First Name":"Bob","Preferred Name":"Bob","Preferred Pronoun":"he/him","SF ID #":"2211-4456","Program Code":"3504","Phone":"910-432-8765","Email":"bob.minion@go.sfcollege.edu"}
期望输出
{"1":{"Last Name":"Minion","First Name":"Bob","Preferred Name":"Bob","Preferred Pronoun":"he/him","SF ID #":"2211-4456","Program Code":3504,"Phone":"910-432-8765","Email":"bob.minion@go.sfcollege.edu"}
输入示例
Last Name,First Name,Preferred Name,Preferred Pronoun,SF ID #,Program Code,Phone,Email Minion,Bob,Bob,he/him,2211-4456,3504,910-432-8765,bob.minion@go.sfcollege.edu Nichols,James,James,,1234-5678,3651,352-395-5220,james.nichols@sfcollege.edu Person,Punny,,,9999-1111,3840,352-123-4567,punny.person@go.sfcollege.edu Person,Punny2,,,9999-1112,3841,352-123-6792,punny2.person@go.sfcollege.edu Person,Punny3,,,9999-1113,3842,352-123-3420,punny3.person@go.sfcollege.edu Smart,Maxwell,Max,,9922-4029,3650,310-2910,agent.smart@go.sfcollege.edu Tree,Groot,Groot,,1122-3344,3624,361-1234-5678,groot.tree@go.sfcollege.edu
问题原因及解决方案
问题核心:从CSV读取的所有值都是字符串类型,原getValueDataType方法里type(value) == int的判断永远不会触发,所有值都会被加上引号。
修改getValueDataType方法,通过尝试转换的方式识别整数、空值、布尔值,再分别处理:
def getValueDataType(self, value): # 处理空值 if not value: return "null" # 尝试转换为整数 try: int_val = int(value) return str(int_val) except ValueError: # 尝试转换为布尔值 lower_val = value.lower() if lower_val == "true": return "true" elif lower_val == "false": return "false" # 其他情况按字符串处理 return f'"{value}"'
修改后,Program Code这类整数值会被正确识别,不再添加引号,符合期望输出格式。
内容的提问来源于stack exchange,提问作者mchlbohn
相关产品推荐
相关产品推荐

