
json转excel
-
2023年2月19日发(作者:)python读取n个⽂件中json格式内容导⼊excel
需求:在⽹上爬取了⼀些⾷物的含量信息,每⼀个⾷品⼀个⽂件,⽂件内容为json格式,需要将这些⾷品信息汇总到⼀个excel中,如下图
⾷物信息⽂件
json内容
汇总后的效果
```
代码块放到这⾥
```
代码块放到这⾥
代码块放到这⾥
importxlrd
importjson
importos
fromopenpyxlimportWorkbook
wb=Workbook()
ws=
cols=[]
defjson2excel(jsfile,excfile):
#读取json数据
a=1
(jsfile):
#先⽤key值写表头
#print(\"111111\")
withopen(jsfile,\'r\',encoding=\'utf8\')asfp:
#先⽤key值写表头
line=ne()
ifnotline:
print(\"没有内容\")
else:
#每⼀⾏转换成字典类型
jsdata=(line)
#⽤key值做标题
#print(\"+++++++++++++++++++++++++++++\"+str(cols))
#print(type(cols))
#print(colsisNone)
#print(len(cols))
iflen(cols)==0:
(\"code\")
(\"name\")
():
ifk==\"ingredient\":
print(\"进⼊key读取\")
ingredient=(\"ingredient\")
#print(())
():
#print(\"==22==2=222----------------\"+c)
(c)
#(\"name\")
(cols)#标题
#print(\"cols======\"+str(cols))
#print()
#写值
withopen(jsfile,\'r\',encoding=\'utf8\')asfp:
#循环写值
whileTrue:
print(\'正在写⼊的⾏数%s:\'%a)
line=ne()
#print(line)
ifnotline:
break
#转换为python对象
jsdata=(line)
rowdata=[]
((\"code\"))
((\"name\"))
forcolincols:
#获取每⼀⾏key值对应的value值
ingredient=(\"ingredient\")
#print(\"==\"+str(ingredient))
(col)isnotNone:
((col))
#print(\"value====\"+str((col)))
#((\"name\"))
#((\"code\"))
#print((\"name\"))
#print(\"-------------------\"+str(rowdata))
a+=1
(rowdata)#写⾏
#(cols)#标题
print(\'保存中\')
(excfile)#保存
if__name__==\'__main__\':
s=1
#path=\"D:/PycharmProjects/jsonExcel/date/\"
path=\"E:/work/data2/\"
files=r(path)
forfinfiles:
filelist=(path+\'/\'+f)
#print(f)
filepath=path+f
print(filepath)
#excfile=\"./\"
excfile=\"./\"
json2excel(filepath,excfile)
#jsfile=\"./_\"
#excfile=\"./\"
#json2excel(jsfile,excfile)