JSON.parse()——Uncaught SyntaxError: Unexpected token \ in JSON at position 1
背景:项目安全处理方面之一 ——对特殊字符进行编解码(后端编码,前端解码)
特殊字符:
" %22
\ %5C
/ %2F
& %26
% %25
' %27
; %3B
[ %5B
] %5D
^ %5E
< %3C
> %3E
Note:均为英文下,中文下不考虑
问题:使用JSON.parse(decodeURIComponent(JSON.stringify(body)))报错 ——Uncaught SyntaxError: Unexpected token / in JSON at position 150
原因:ECMA script注明json字符串中需要转义的字符: " / \ b f n r t
思路:
1、JSON.stringify()之后替换特殊字符
2、decodeURIComponent()之后替换特殊字符
解决:
经验证,特殊字符需要替换为“\特殊字符”,再使用JSON.parse()可以解决。
1、\必须最先替换,防止多余替换其他特殊字符之前的\;
2、"必须在JSON.stringify()之后替换,若在decodeURIComponent()之后替换,会将json结构属性,和属性名的"也替换;
3、\和b f n r t结合,JSON.parse()也会报错,但单独存在不会被编码。
JSON.parse(decodeURIComponent(
JSON.stringify(body).replace(/%5C/g,'%5C%5C')
.replace(/%22/g,"%5C%22")
.replace(/%2F/g,'%5C%2F')
.replace(/%08/g,'%5Cb')
.replace(/%0C/g,'%5Cf')
.replace(/%0A/g,'%5Cn')
.replace(/%0D/g,'%5Cr')
.replace(/%09/g,'%5Ct')));
注:
body =
{
"code": 0,
"message": "success",
"data": {
"offeringBasicList": [{
"offeringId": 2019000167,
"classifyId": 1000000009,
"classifyName": "IOT",
"offeringCode": "%3B%3C%3E%27%22%2F%5C%40%23%24%25%5E%26*%28%29%5B%5Dabcd",
"offeringName": "%3C%3E%27%22%2F%5C%40%23%24%25%5E%26*%28%29%5B%5Dabcd",
"offeringShortName": "%3C%3E%27%22%2F%5C%40%23%24%25%5E%26*%28%29%5B%5Dabcd",
"offeringDesc": "%3C%3E%27%22%2F%5C%40%23%24%25%5E%26*%28%29%5B%5Dabcd",
"isBundled": "N",
"ownerPartyRole": "CA",
"ownerPartyId": "0ff08435-aa1b-49d5-9780-5384d4989c9e",
"releasePartyRole": null,
"releasePartyId": null,
"isPrimary": "Y",
"maxNum": null,
"minNum": null,
"beId": "101",
"orgId": null,
"createdBy": "0ff08435-aa1b-49d5-9780-5384d4989c9e",
"createdTime": 1526623849854,
"updatedBy": "0ff08435-aa1b-49d5-9780-5384d4989c9e",
"updatedTime": 1526623849854,
"thumbnailName": null,
"thumbnailDesc": null,
"thumbnailUrl": null,
"busiModeType": null,
"status": {
"key": "DRA",
"value": "Draft"
},
"ownerType": {
"key": "S",
"value": "Subscriber"
}
}],
"pageInfo": {
"beginRowNumber": 0,
"sortField": "created_time",
"totalRecord": 1
}
}
}
扩展:
1、URI标准不允许使用保留字符,如/,解决:
encodeURIComponent() 编码
decodeURIComponent() 解码
既可编码保留字符,又可编码多字节字符
2、decodeURIComponent()解码包含'%'的字符串时,若%与之后的字符无法转义为正常字符串会报错,eg:'90%';