1、為什么要進行CSV與JSON格式之間的轉換
CSV格式常用於一二維數據表示和存儲,他是一種純文本形式存儲表格數據的表示方式。JSON也可以表示一二維數據。在網絡信息傳輸中,可能需要統一表示方式,因此,需要在CSV和JSON格式間進行相互轉換。
2、代碼
csv轉json:
student_csv=[]; student_json=[]; with open("student.csv",mode='r',encoding='ansi')as student_csv_file_name: read_object=csv.reader(student_csv_file_name); #用csv模塊自帶的函數來完成讀寫操作 with open("student_csv轉json.json",mode='w',encoding='ansi')as student_json_file_name: for i in read_object: student_csv.append(i); key=student_csv[0]; for i in range(1,len(student_csv)): student_json_temp=[]; for j in zip(key,student_csv[i]): k=":".join(j); student_json_temp.append(k); student_json.append(student_json_temp); json.dump(student_json,student_json_file_name);
json轉csv:
student_csv=[]; student_json=[]; with open("student.json",mode='r',encoding='ansi')as student_json_file_name: with open("student_json轉csv.csv",mode='w',encoding='ansi',newline='')as student_csv_file_name: read_object=json.load(student_json_file_name); write=csv.writer(student_csv_file_name); for i in read_object: #讀出來是列表 ledlist=[]; templist=[]; for a in i: j=a.split(':'); ledlist.append(j[0]); templist.append(j[1]); if len(student_csv)==0: student_csv.append(ledlist); student_csv.append(templist); for i in student_csv: write.writerow(i);