zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python代码实现Excel转JSON

2023-06-13 09:11:57 时间

大家好,又见面了,我是你们的朋友全栈君。

题记

项目需求需要用到Excel转JSON,第一时间想到的就是尘封了将近一年的python,一直在JavaJava,python早忘光了,想立刻开始动手却又不敢,最后确认,用python来完成操作Excel有得天独厚的优势,只能硬着头皮上了。短短的代码,做了将近四个小时,中间复习了一下字典和列表,同时也因为其中遇到了一些奇奇怪怪的问题,凌晨一点多躺下,一身轻松。

主要技术

python 3.8.6 + 字典/列表的运用 +对Excel操作的库pandas

其中python对Excel操作的库其实有很多,像我以前也用过xlrdxlwtopenpyxl等等等,但也各有优缺点吧,有的mac和win不兼容,而像pandas只支持加载表的单个sheet,但在这个工作任务中够用了,大家如果需要对Excel进行操作,可以根据项目/任务需求选择,这边不再赘述。但对Excel转JSON而言,无论用什么库,其核心都是对列表和字典的运用

Excel部分数据展示

希望效果

由门类到专业类到专业的JSON数据

最终的代码实现

import pandas as pd
import json

data = pd.read_excel(r'/Users/wanglingyi/Desktop/Excel转json/2020本科专业目录.xlsx',sheet_name='汇总')

json_list = []
for name in data['门类'].unique():                           #选门类 
    name_dict={ 
   }                    #建立该门类的字典,存储该门类的名字和专业类及其信息 
    name_dict['name'] = name                                 #存储门类名字 
    name_options = []                                        #准备存储信息 
    name_data = data[data['门类']==name]                     #数据降级 
    #print(name_data) #逐层检查数据是否正确

    for kind in name_data['专业类'].unique():                 #选专业类 
        kind_dict={ 
   }                                         #建立专业类字典,放专业类名字和信息 
        kind_dict['name'] = kind                             #存储专业类名字 
        options = []                                       	 #准备存储信息
        kind_data = name_data[name_data['专业类']==kind]      #数据降级
        #print(kind_data) #逐层检查数据是否正确
        
				#定专业,专业代码唯一,所以不再限定
        for code in kind_data['专业代码']:                            
            #根据上面推出要找代码一样的数据
            code_data = kind_data[kind_data['专业代码']== code ]       
            info = { 
   }                                      #取数据
            info['code'] = code                                      
            for name in code_data['专业名称']:
                info['name'] = name
            for grant in code_data['学位授予门类']:
                info['grant'] = grant
            for years in code_data['修业年限']:
                info['years'] = years
            #print(info) #逐层检查数据是否正确
            options.append(info)
            #print(options) #逐层检查数据是否正确

        kind_dict['options'] = options                   #填充数据
        name_options.append(kind_dict)

    name_dict['options'] = name_options
    json_list.append(name_dict) 
    #print(json_list) #展示结果(先预览看一下)

#确定结果格式正确后以文件形式输出
json_dict = { 
   }
json_dict['data'] = json_list
data_dict = json.dumps(json_dict, ensure_ascii=False)
with open('data.json','w') as f_w:
        f_w.write(data_dict)

部分结果展示(已经通过JSON在线预览器美化)

{ 
   
  "data": [
    { 
   
      "name": "哲学",
      "options": [
        { 
   
          "name": "哲学类",
          "options": [
            { 
   
              "code": "010101",
              "name": "哲学",
              "grant": "哲学",
              "years": "四年"
            },
            { 
   
              "code": "010102",
              "name": "逻辑学",
              "grant": "哲学",
              "years": "四年"
            },
            { 
   
              "code": "010103K",
              "name": "宗教学",
              "grant": "哲学",
              "years": "四年"
            },
            { 
   
              "code": "010104T",
              "name": "伦理学",
              "grant": "哲学",
              "years": "四年"
            }
          ]
        }
      ]
    }
   ]
} .........

原文件展示

注意事项

1.理清json数据结构关系

2.注意文件路径前的 r(可以去掉试试会发生什么)

3.可以逐层打印每个数据,看看是否符合格式,从而避免从头到尾都是错的。这就是为什么我在代码中出现了很多**#print()**。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/137516.html原文链接:https://javaforall.cn