Postman修改预请求脚本上的JSON



在Postman上发送下一个POST请求之前,我正在尝试修改JSON主体。

这个想法是做一个GET,然后在再次张贴之前修改正文。

第一部分很好——GET然后将值保存在Postman变量上。

在现有JSON主体上添加数组时遇到问题。

JSON正文

{
"Common": {
"Shared": {
"name": "test",
"test_policy": {
"rules": [
{
"name": "default",
"actions": [
{
"type": "block",
"enabled": true,
}

]
}
],
}
}
}
}

然后我需要添加另一个";规则";根据"规则":

{
"Common": {
"Shared": {
"name": "test",
"test_policy": {
"rules": [
{
"name": "rule0",
"actions": [
{
"type": "accept",
"enabled": true,
}

]
},
{
"name": "default",
"actions": [
{
"type": "block",
"enabled": true,
}

]
}
],
}
}
}
}

测试GET请求(工作正常(

let response = pm.response.json();
savedData = JSON.stringify(response);
pm.environment.set("declaration", savedData);

POST上的预请求不起作用,我一直收到一个";declaration.push不是函数";

var rule = '{"name": "rule0","actions": [{"type": "accept","enabled": true,}]}';
let rule_obj = JSON.parse(rule);
let declaration_obj = JSON.parse(pm.variables.get("declaration"));
declaration_obj.push(rule_obj)
newDeclaration = JSON.stringify(declaration_obj);
pm.environment.set("newDeclaration", newDeclaration);

欢迎任何帮助。

谢谢!

let declaration_obj = JSON.parse(pm.variables.get("declaration"));

declaration_obj.Common.Shared.test_policy.rules.push(rule_obj)

您应该调用rules属性,然后对其调用push。不在主json对象上

最新更新