相关文章推荐
会搭讪的石榴  ·  神经网络调参:loss ...·  1 年前    · 
温暖的金鱼  ·  MVVM WPF ComboBox ...·  1 年前    · 
嵌入app 内的H5页面在于原生通过jsSdk 交互中存在数据传输交互,原生部分特殊字符在JSON stringify 时未对特殊字符进行转译处理,导致H5页面接收到数据进行JSON parse 时报错进而导致页面异常。

处理方法:

对未转译的反斜杠和双引号 及 \n \r \t 进行转译处理后再执行JSON parse
let jsonResult = receiveJsonString
jsonResult = jsonResult.replace(/\\/g, '\\\\')
jsonResult = jsonResult.replace(/\n/g, '\\n')
jsonResult = jsonResult.replace(/\r/g, '\\r')
jsonResult = jsonResult.replace(/\t/g, '\\t')
jsonResult = _cleanseJSON(jsonResult)
let resultModel = {}
try {
    resultModel = JSON.parse(jsonResult)
} catch (error) {
    console.log(error, '----------parse error')
    resultModel = null
console.log(resultModel, '---------resultModel')
if (!resultModel) {
    Toast(`输入中包含非法字符,请返回重新输入`)
    return
const _cleanseJSON = function (jsonStr) {
  for (var k = 0; k < jsonStr.length; k++) {
    if (jsonStr.charAt(k) === '"') {
      var prevChar = jsonStr.charAt(k - 1)
      // var prevChar2 = jsonStr.charAt(k - 2)
      var nextChar = jsonStr.charAt(k + 1)
      var nextChar2 = jsonStr.charAt(k + 2)
      var esc = '\\'
      var isValid = false
      var prevFix = false
      var postFix = false
      switch (prevChar) {
        case ':':
        case '{':
        case ',':
        case '[':
        case '\\': // already escaped
          isValid = true
          break
        default:
          prevFix = true
      switch (nextChar) {
        case ':':
        case '}':
        case ',':
          if (nextChar2 === ' ') { // if there is a comma, but the next is a space consider it invalid JSON
            break
        case ']':
        case '\\': // already escaped
          isValid = true
          break
        default:
          postFix = true
      // first test to ensure the quote is likely bogus
      if (!isValid) {
        if (prevFix) {
          jsonStr = [jsonStr.slice(0, k), esc, jsonStr.slice(k)].join('')
        } else {
          if (postFix) {
            jsonStr = [jsonStr.slice(0, k + 1), esc, jsonStr.slice(k + 1)].join('')
      } // if not valid "
    } // if we find a doublequote
  return jsonStr