CSV and JSON format conversion

1. Why convert between CSV and JSON format

  CSV format commonly used in a two-dimensional data representation and storage, he is a pure representation of text stored tabular data. JSON can also represent a two-dimensional data. In the information transmission network, a unified representation may be necessary, therefore, the need for mutual conversion between CSV and JSON format.

2, the code

  csv turn 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 turn 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);

 

Guess you like

Origin www.cnblogs.com/c1q2s3/p/12003070.html