Postman接口测试过程中,我们时常需要将某一接口的返回数据,提取作为参数,供其他接口使用。这时我们可以通过断言tests解析响应数据,提取所需字符串。
测试API接口:
https://www.juhe.cn/docs/api/id/39
请求参数要求参照API规范。
要求:将响应数据中sk的“wind_direction”的值赋给全局变量respjson
响应数据:
{
"resultcode": "200",
"reason": "successed!",
"result": {
"sk": {
"temp": "22",
"wind_direction": "西北风",
"wind_strength": "4级",
"humidity": "49%",
"time": "13:55"
},
"today": {
"temperature": "15℃~23℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风3-5级",
"week": "星期五",
"city": "苏州",
"date_y": "2019年10月18日",
"dressing_index": "舒适",
"dressing_advice": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。",
"uv_index": "弱",
"comfort_index": "",
"wash_index": "较适宜",
"travel_index": "较适宜",
"exercise_index": "较适宜",
"drying_index": ""
},
"future": {
"day_20191018": {
"temperature": "15℃~23℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风3-5级",
"week": "星期五",
"date": "20191018"
},
"day_20191019": {
"temperature": "14℃~23℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"wind": "北风微风",
"week": "星期六",
"date": "20191019"
},
"day_20191020": {
"temperature": "15℃~23℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东风微风",
"week": "星期日",
"date": "20191020"
},
"day_20191021": {
"temperature": "16℃~24℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东北风微风",
"week": "星期一",
"date": "20191021"
},
"day_20191022": {
"temperature": "17℃~23℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东风微风",
"week": "星期二",
"date": "20191022"
},
"day_20191023": {
"temperature": "14℃~23℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"wind": "北风微风",
"week": "星期三",
"date": "20191023"
},
"day_20191024": {
"temperature": "16℃~24℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东北风微风",
"week": "星期四",
"date": "20191024"
}
}
},
"error_code": 0
}
在断言(tests)中添加提取代码
//获取JSON格式的响应数据
var jsonData=JSON.parse(responseBody);
//提取响应数据中sk.wind_direction的值赋给全局变量respjson
pm.globals.set("respjson", jsonData.result.sk.wind_direction);
执行接口,查看变量。
可以将该变量做为其他接口的请求参数。
如果json里有数组,可以按照数组的序号提取,编号规则从0开始。例如:
{
“resultcode”: “100”,
“list”: [
{
“id”: 1339,
“name”: “李明”,
},
{
“id”: 1340,
“name”: “韩梅梅”,
},
{
“id”: 1341,
“name”: “王斌”,
}
],
“total”: 33
}
要提取第二组name韩梅梅
var jsonData=JSON.parse(responseBody);
pm.globals.set("name", jsonData.list[1].name);