1. 问题描述
在使用postman
进行接口测试的时候,总是会碰到一个问题,请求参数如果是 json 格式时是不支持注释的,会将注释也一并发送出去,后端接受后可能会导致数据不正确。
如果后端没有进行特殊处理,会报错json parse error
解析错误。
2. 解决方法
解决方法可以提供三种:
- 更换接口工具,支持
//
注释的 - 在
json
请求体中添加【冗余注释】 - 添加前置预处理脚本,处理
json
请求体中的注释信息
2.1 更换工具
更换postman
接口测试工具,换成支持//
注释的工具,比如ApiPost
。
2.2 在json
请求体中添加【冗余注释】
添加冗余_{key}.comment
标明注释,实现在json请求体中添加注释。
{
"id": "12",
"_id.comment":"表id"
"name": "<script>alert('正在发动xss攻击')</script><a href='http://www.baidu.com' target='xxxx' style='color:red'>澳门皇家赌场上线了<a>",
"_name.comment":"表name"
}
2.3 添加前置预处理脚本
使用正则匹配的方法,利用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;
// found a " character, and we're not currently in
// a comment? check for previous `\` escaping immediately
// leftward adjacent to this match
if (tmp[0] === "\"" && !in_multiline_comment && !in_singleline_comment) {
// limit left-context matching to only go back
// to the position of the last token match
//
// see: https://github.com/getify/JSON.minify/issues/64
lc.lastIndex = prevFrom;
// perform leftward adjacent escaping match
tmp2 = lc.match(/(\\)*$/);
// start of string with ", or unescaped " character found to end string?
if (!in_string || !tmp2 || (tmp2[0].length % 2) === 0) {
in_string = !in_string;
}
from--; // include " character in next catch
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)