Postman全局变量传递时如何保留双引号?API请求报错解决
解决Postman全局变量传递时UUID双引号丢失的问题
问题场景
我在Postman中编写了如下JavaScript脚本提取UUID数组:
// Parse the response body as JSON var response = JSON.parse(responseBody); // Create an empty array to store the id values var ids = []; // Loop through each item in the response array response.response.forEach(function(item) { ids.push(item.id); }); // Log the ids array to the console console.log(ids); // Set the ids array as a global variable pm.globals.set("ids", ids); console.log(pm.environment.get("ids"));
之后在另一个POST请求体中引用该全局变量:
{ "name" : "show ver and show inventory", "commands" : ["show ver", "show inventory"], "deviceUuids" : [{{ids}}] }
请求报错:bad request error, There was an error processing the input arguments,查看控制台发现deviceUuids内的UUID无双引号,而正确格式应为每个UUID带双引号的数组:
{ "name" : "show ver and show inventory", "commands" : ["show ver", "show inventory"], "deviceUuids" : ["0a6602ef-2416-4702-a40b-c79308c8a489", "85c7a7c4-c578-46d3-9a4b-b84dc6b2a25e", "c5ed30a3-9c21-4e01-b70b-2621b8bc09ad", "dd1700bc-4310-47c8-a1f9-e2f5840838b5"] }
解决方案
问题核心是变量存储格式和引用方式不符合JSON规范,调整如下:
1. 修改变量存储逻辑,转为JSON字符串
Postman直接存储数组时,会自动转为无引号的逗号分隔字符串,需用JSON.stringify()将数组转为标准JSON格式字符串后再存储:
// 替换原pm.globals.set行,将数组转为JSON字符串存储 pm.globals.set("ids", JSON.stringify(ids));
2. 调整请求体中的变量引用方式
由于存储的已是完整的JSON数组(包含双引号和数组结构),请求体中直接用{{ids}}替换整个deviceUuids的值,无需额外包裹数组括号:
{ "name" : "show ver and show inventory", "commands" : ["show ver", "show inventory"], "deviceUuids" : {{ids}} }
原理说明
JSON.stringify(ids)会把数组转为["uuid1", "uuid2"]这类符合JSON规范的字符串,保留双引号和数组结构。- 请求体中直接引用变量后,Postman会将其替换为完整的JSON数组,完全匹配接口要求的格式。
内容的提问来源于stack exchange,提问作者afranco.pt
相关产品推荐
相关产品推荐

