一、问题描述
通过 JSON.parse 方法在 iOS 平台解析某段字符串失败,但在 Android 平台却正常
二、原因分析
对于深度嵌套的JSON字符串,使用 JSON.parse 进行解析时,会出现代码错误,可能包含特殊字符。导致解析报错,JSON.parse报错
三、解决方案
使用正则进行报错格式和特殊字符的替换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export function handleSpecialCharacters(jsonStr) { let obj = {}; if (jsonStr && Object.prototype.toString.call(jsonStr) == "[object String]" && jsonStr != 'null') { jsonStr = jsonStr.replace(/\r/g, "\\r"); jsonStr = jsonStr.replace(/\n/g, "\\n"); jsonStr = jsonStr.replace(/\t/g, "\\t"); jsonStr = jsonStr.replace(/\\/g, "\\\\"); jsonStr = jsonStr.replace(/\'/g, "'"); jsonStr = jsonStr.replace(/ /g, " "); jsonStr = jsonStr.replace(/</g, "$lt;"); jsonStr = jsonStr.replace(/>/g, "$gt;"); obj = JSON.parse(jsonStr) } return obj; }
|
四、过程记录
无
五、总结备忘
后端传到客户端同样的字符串可能因为 iOS 和 Android 平台差异而显示异常,同时实现两端相关显示时需要充分对比测试。