背景
Pandas中的DataFrame对象可以使用内置的.to_json()
方法转换为json格式的字符串,但是如果直接将这个字符串通过Flask返回给浏览器的话,看到的只是个字符串,并不是json对象.
@bp.route('/detail')
def get_detail():
# 省略df的创建过程
jdata = df.to_json(orient='records', force_ascii=False)
return jdata
实验
使用Flask中的jsonify()
将df.to_json()
转换的json字符串进行处理后返回浏览器变成json对象了,但是格式不正确,还是个字符串.
@bp.route('/detail')
def get_detail():
# 省略df的创建过程
jdata = df.to_json(orient='records', force_ascii=False)
return jsonify(jdata)
解决方法
使用Python内置json
库的json.loads()
方法先将df.to_json
转换的字符串加载为Python内置的json对象,然后再使用Flask的jsonify
进行返回
@bp.route('/detail')
def get_detail():
# 省略df的创建过程
jdata = df.to_json(orient='records', force_ascii=False)
return jsonify(json.loads(jdata))