postman中为JSON数据写注释信息 |
您所在的位置:网站首页 › 请求json格式不正确 › postman中为JSON数据写注释信息 |
索引
问题描述解决方案添加方法处理效果
预处理函数代码
问题描述
在使用postman进行接口测试的时候,总是会碰到一个问题,请求参数如果是 json 格式时是不支持注释的,会将注释也一并发送出去,后端接受后可能会导致数据不正确。 使用正则匹配的方法,利用Pre-request Script(前置脚本)预处理发送出去的JSON格式信息 添加方法
方法代码如下: //去除json参数中的注释信息 GlobalJsonMinify = function (json) { var tokenizer = /"|(\/\*)|(\*\/)|(\/\/)|\n|\r|\[|]/g, in_string = false, in_multiline_comment = false, in_singleline_comment = false, tmp, tmp2, new_str = [], ns = 0, from = 0, lc, rc, prevFrom ; tokenizer.lastIndex = 0; while ( tmp = tokenizer.exec(json) ) { lc = RegExp.leftContext; rc = RegExp.rightContext; if (!in_multiline_comment && !in_singleline_comment) { tmp2 = lc.substring(from); if (!in_string) { tmp2 = tmp2.replace(/(\n|\r|\s)*/g,""); } new_str[ns++] = tmp2; } prevFrom = from; from = tokenizer.lastIndex; if (tmp[0] === "\"" && !in_multiline_comment && !in_singleline_comment) { lc.lastIndex = prevFrom; tmp2 = lc.match(/(\\)*$/); if (!in_string || !tmp2 || (tmp2[0].length % 2) === 0) { in_string = !in_string; } from--; rc = json.substring(from); } else if (tmp[0] === "/*" && !in_string && !in_multiline_comment && !in_singleline_comment) { in_multiline_comment = true; } else if (tmp[0] === "*/" && !in_string && in_multiline_comment && !in_singleline_comment) { in_multiline_comment = false; } else if (tmp[0] === "//" && !in_string && !in_multiline_comment && !in_singleline_comment) { in_singleline_comment = true; } else if ((tmp[0] === "\n" || tmp[0] === "\r") && !in_string && !in_multiline_comment && in_singleline_comment) { in_singleline_comment = false; } else if (!in_multiline_comment && !in_singleline_comment && !(/\n|\r|\s/.test(tmp[0]))) { new_str[ns++] = tmp[0]; } } new_str[ns++] = rc; return new_str.join(""); }; pm.request.body.raw = GlobalJsonMinify(pm.request.body.raw) |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |