json 用于浏览器和服务器进行数据传输的一种数据格式
1,接收json,并通过json.loads处理为字典,result已经变为dict字典数据类型
from flask import Flask
import json
app = Flask(__name__)
@app.route('/')
def demo2():
json_demo = '{"age": 18, "name": "小明", "class": "7"}'
# dumps将json转换为字典
result = json.loads(json_demo)
return result
if __name__ == '__main__':
app.run(debug=True)
通过json.dumps方法将字典转换为json数据类型返回给前端,result转换为json类型的字符串
from flask import Flask
import json
app = Flask(__name__)
@app.route('/')
def demo1():
json_dict = {"age": 18, "name": "小明", "class": "7"}
# dumps将字典转换为json
result=json.dumps(json_dict,ensure_ascii=False)
print(type(result))
return result
if __name__ == '__main__':
app.run(debug=True)
通过flask框架中的jsonify将字典类型的数据转化为json返回给前端
from flask import Flask,jsonify
app = Flask(__name__)
@app.route('/')
def demo1():
json_demo = {"age": 18, "name": "小明", "class": "7"}
# jsonify将字典转为json,并返回给前端content-type:application/json
return jsonify(json_demo)
if __name__ == '__main__':
app.run(debug=True)
json数据,中文无法展示,app配置中将JSON_AS_ASCII设置为False
from flask import Flask,jsonify
app = Flask(__name__)
# 解决浏览器中json数据,中文无法展示的问题
app.config['JSON_AS_ASCII']=False
@app.route('/')
def demo1():
json_demo = {"age": 18, "name": "小明", "class": "7"}
# jsonify将字典转为json,并返回给前端content-type:application/json
return jsonify(json_demo)
if __name__ == '__main__':
app.run(debug=True)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)