I'm trying to modify a JSON body before sending the next POST request on Postman.
The idea is the do a GET then modify the body before POSTing it again.
The first part is fine - GET then save value on a Postman variable.
I'm having trouble adding an array on the existing JSON body.
JSON Body
{
"Common": {
"Shared": {
"name": "test",
"test_policy": {
"rules": [
{
"name": "default",
"actions": [
{
"type": "block",
"enabled": true,
}
]
}
],
}
}
}
}
Then I need to add another "rule" under 'rules' as such:
{
"Common": {
"Shared": {
"name": "test",
"test_policy": {
"rules": [
{
"name": "rule0",
"actions": [
{
"type": "accept",
"enabled": true,
}
]
},
{
"name": "default",
"actions": [
{
"type": "block",
"enabled": true,
}
]
}
],
}
}
}
}
Tests on GET request (that works fine)
let response = pm.response.json();
savedData = JSON.stringify(response);
pm.environment.set("declaration", savedData);
Pre-Request on POST is not working, I keep getting a "declaration.push is not a function"
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);
Any help will be welcome.
Thanks!
CodePudding user response:
let declaration_obj = JSON.parse(pm.variables.get("declaration"));
declaration_obj.Common.Shared.test_policy.rules.push(rule_obj)
you should call the rules property and then call push on it . not on the main json object