如何用前序请求响应更新JSON变量并发送HTTP请求?
如何用上一个HTTP响应更新JSON变量
以下分两种常见场景给出具体实现方案:
一、用API测试工具(以Postman为例)
- 发送第一个请求后,在Tests标签页中编写脚本,把响应值存入环境/全局变量:
// 假设第一个请求响应是 {"userId": 123, "userName": "Alice"} const responseData = pm.response.json(); pm.environment.set("targetUserId", responseData.userId); pm.environment.set("targetUserName", responseData.userName); - 编辑你的JSON内容(直接写在请求体或本地文件中),用
{{变量名}}作为占位符:{ "user_id": "{{targetUserId}}", "user_name": "{{targetUserName}}", "other_field": "固定值" } - 发送第二个请求时,工具会自动替换变量为之前存储的响应值。如果是本地JSON文件,可通过Pre-request Script读取文件并完成变量替换后再发送请求。
二、用代码实现(以Python为例)
如果需要自动化流程,用代码处理更灵活:
- 发送第一个请求并解析响应:
import requests import json # 发送第一个请求获取数据 first_res = requests.get("https://your-api-url/first-endpoint") # 确保请求成功再继续 if first_res.status_code != 200: raise Exception(f"第一个请求失败,状态码: {first_res.status_code}") response_data = first_res.json() - 读取并更新本地JSON文件:
# 读取原始JSON文件 with open("your-variables.json", "r", encoding="utf-8") as f: json_vars = json.load(f) # 更新指定变量 json_vars["user_id"] = response_data["userId"] json_vars["user_name"] = response_data["userName"] # 可选:保存更新后的JSON文件 with open("updated-variables.json", "w", encoding="utf-8") as f: json.dump(json_vars, f, indent=2, ensure_ascii=False) - 用更新后的JSON发送第二个请求:
# 发送第二个请求 second_res = requests.post( "https://your-api-url/second-endpoint", json=json_vars ) print(f"第二个请求响应状态码: {second_res.status_code}")
常见问题排查
- 确认第一个请求的响应格式是JSON,若不是需先转换格式(比如文本转JSON)。
- 检查变量名/键名是否完全匹配,避免拼写错误导致赋值失败。
- 用工具时注意变量的作用域(环境变量仅当前环境有效,全局变量全 workspace 有效)。
内容的提问来源于stack exchange,提问作者Agathiyan
相关产品推荐
相关产品推荐

