简体   繁体   中英

Postman Modify JSON on Pre-Request Script

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 is welcome.

Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM