utils.ts 1.02 KB
import { excludeParseEventKeyList, excludeParseEventValueList } from "@/enums/eventEnum"

const tryRunFunction = (v: string) => {
  try {
    return eval(`(function(){return ${v}})()`)
  } catch (error) {
    return v
  }
}

export const JSONParse = (data: string) => {
  return JSON.parse(data, (k, v) => {
    // 过滤函数字符串
    if (excludeParseEventKeyList.includes(k)) return v
    // 过滤函数值表达式
    if (typeof v === 'string') {
      const someValue = excludeParseEventValueList.some(excludeValue => v.indexOf(excludeValue) > -1)
      if (someValue) return v
    }
    // 还原函数值
    if (typeof v === 'string' && v.indexOf && (v.indexOf('function') > -1 || v.indexOf('=>') > -1)) {
      return tryRunFunction(v)
    } else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
      const baseLeftIndex = v.indexOf('(')
      if (baseLeftIndex > -1) {
        const newFn = `function ${v.substring(baseLeftIndex)}`
        return tryRunFunction(newFn)
      }
    }
    return v
  })
}