DataFrame转json格式

python代码开发完成后,需要对接前端时,往往需要把dataframe格式转为json格式,函数如下:

import pandas as pd
import json
   
def to_json2(df,orient='split'):
    df_json = df.to_json(orient = orient, force_ascii = False)
    return json.loads(df_json)

创建一个DataFrame:

test_dict = {'id':[1,2,3,4,5,6],'name':['Alice','Bob','Cindy','Eric','Helen','Grace '],'math':[90,89,99,78,97,93],'english':[89,94,80,94,94,90]}
#[1].直接写入参数test_dict
test_dict_df = pd.DataFrame(test_dict)

打印一下:

test_dict_df
Out[30]: 
   id    name  math  english
0   1   Alice    90       89
1   2     Bob    89       94
2   3   Cindy    99       80
3   4    Eric    78       94
4   5   Helen    97       94
5   6  Grace     93       90

转为json:

to_json2(test_dict_df)
Out[31]: 
{'columns': ['id', 'name', 'math', 'english'],
 'index': [0, 1, 2, 3, 4, 5],
 'data': [[1, 'Alice', 90, 89],
  [2, 'Bob', 89, 94],
  [3, 'Cindy', 99, 80],
  [4, 'Eric', 78, 94],
  [5, 'Helen', 97, 94],
  [6, 'Grace ', 93, 90]]}

返回给前端

def to_fronrend(data):
	return {"data": data}
to_fronrend(to_json2(test_dict_df))

Out[33]: 
{'data': {'columns': ['id', 'name', 'math', 'english'],
  'index': [0, 1, 2, 3, 4, 5],
  'data': [[1, 'Alice', 90, 89],
   [2, 'Bob', 89, 94],
   [3, 'Cindy', 99, 80],
   [4, 'Eric', 78, 94],
   [5, 'Helen', 97, 94],
   [6, 'Grace ', 93, 90]]}}

你可能感兴趣的:(df,转,json,json,python)