JSOIN.parse()报错:Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse ...

I encountered a problem in the project: the front end needs to convert the json string returned by the background into a json object, but the string returned from the background contains escape characters : \"

First, determine a problem

JSON.parse() parameter needs to be of type string  

Since the passed parameter is of object type, JSON.parse() will convert the object type to string by default and the result is "[object object]"  

2. If it is a string but still escapes and reports an error, it may be due to escape characters and other reasons that it cannot be escaped. Finally, the method found on the Internet can be handled as follows:

var json = eval('(' + data + ')');

But in the eslint format, the eval function will report a warning: eval is harmful

Optimized:

jsonEval (fn) {
      var Fun = Function // 一个变量指向Function,防止有些前端编译工具报错
      return new Fun('return ' + fn)()
    },

let str = this.jsonEval(res.data.TargetText)

This will solve it.

Guess you like

Origin blog.csdn.net/weixin_50114203/article/details/130410387