【问题标题】:Postman Modify JSON on Pre-Request Script邮递员在预请求脚本上修改 JSON
【发布时间】:2021-12-21 12:11:39
【问题描述】:

我正在尝试在 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);

欢迎任何帮助。

谢谢!

【问题讨论】:

  • declaration_obj 里面有什么,push 是只支持数组的方法
  • declaration_obj 是来自第一个 sn-p 的 JSON 正文,我从之前要修改的 GET 中获得。

标签: javascript json postman


【解决方案1】:
let declaration_obj = JSON.parse(pm.variables.get("declaration"));



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

你应该调用 rules 属性,然后调用 push 。不在主要的 json 对象上

【讨论】:

  • 完美,感谢它成功了!
猜你喜欢
  • 1970-01-01
  • 2022-06-12
  • 2015-10-26
  • 2020-03-11
  • 2020-03-21
  • 1970-01-01
  • 2018-05-29
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多