简化GET请求结果表单JSON的过程通常涉及以下几个方面:
原因:
解决方法:
假设原始JSON如下:
{
"user": {
"id": 123,
"name": "John Doe",
"contact": {
"email": "john.doe@example.com",
"phone": "123-456-7890"
},
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
}
简化后的JSON可以只包含用户的基本信息:
{
"userId": 123,
"userName": "John Doe",
"userEmail": "john.doe@example.com"
}
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id):
# 假设这是从数据库获取的用户信息
user_info = {
"id": user_id,
"name": "John Doe",
"contact": {
"email": "john.doe@example.com",
"phone": "123-456-7890"
},
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
# 简化后的数据
simplified_user = {
"userId": user_info["id"],
"userName": user_info["name"],
"userEmail": user_info["contact"]["email"]
}
return jsonify(simplified_user)
if __name__ == '__main__':
app.run(debug=True)
通过这种方式,可以有效简化GET请求返回的JSON数据,使其更易于处理和使用。
领取专属 10元无门槛券
手把手带您无忧上云