将excel的数据导入,并想用echarts进行可视化,出现了错误
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, bytes):
return str(obj, encoding='utf-8')
return json.JSONEncoder.default(self, obj)
@app.route('/')
def get_data():
# 读取excel数据
import pandas as pd
io=r'C:\Users\86137\Desktop\python\2020水资源.xlsx'
work_book = pd.read_excel(io,sheet_name=0,index_col=[0],usecols=[0,4],skiprows=[0,1,2,3,4])
category=work_book.index
value = work_book.values
data={'category':category,'value':value}
return json.dumps(data,ensure_ascii=False,cls=MyEncoder, indent=4)
TypeError: Object of type Index is not JSON serializable
添加了MyEncoder,但还是同样的错误
work_book.index 和 work_book.value 是 pandas中的对象是不能用json.dumps()转为json字符串的
要用.tolist()转成列表才行
category=work_book.index.tolist()
value = work_book.values.tolist()
data={'category':category,'value':value}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
根据你需要的格式,再去组织json样式
import json
import pandas as pd
import numpy as np
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
def get_data():
# 读取excel数据
io=r'D:\Codes\python\demo01\data.xlsx'
work_book = pd.read_excel(io,sheet_name=0,usecols=[0,1])
category= work_book.index
value = work_book.values
data={'category':category,'value':value}
return json.dumps(data,ensure_ascii=False,cls=MyEncoder, indent=4)
print(get_data())