当前位置:网站首页>[unexpected token o in JSON at position 1 causes and solutions]

[unexpected token o in JSON at position 1 causes and solutions]

2022-06-25 08:11:00 Xingyu 1969

Unexpected token o in JSON at position 1 Causes of errors and solutions


Current end use JSON.parse When parsing the data returned by the server, it will report (Unexpected token o in JSON at position 1) error . The reason is that the returned data is an object , In use JSON.parse If you go to parse it, it will be redundant and an error will be reported . The solution can be solved by adding a judgment in the following way
Here are some Inline code slice .

 			var joinObj
            var message;
            var code;
            var typeStr = typeof(result)
            if (typeStr == 'object'){
                
                message = result.message;
                code = result.code;
            } else if(typeStr == 'string'){
    
                joinObj = JSON.parse(result)
                message = joinObj.message
                code = joinObj.code
            }  
            if(code === 0) {
                  
                return window.alert(message);
            }
            else if(code === 1){
                  
                window.location.href = '/login.html'
                return window.alert(message);
            }

among result Is the data returned by the server , Use typeof Resolves the return value type , If it is object Type is not used JSON.parse(result) Otherwise use JSON.parse Generate an object . So you can get the attribute method .

原网站

版权声明
本文为[Xingyu 1969]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250603002500.html