Uncaught SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse (<anonymous>)
下面这个函数可以判断字符串是否为JSON格式,如果是,则返回true。如果不是,也不会报错,而是用try catch盖住报错,抛出异常,并返回false:
01 | function isJSON(str) { |
02 | if ( typeof str == 'string' ) { |
03 | try { |
04 | var obj=JSON.parse(str); |
05 | if ( typeof obj == 'object' && obj ){ |
06 | return true ; |
07 | } else { |
08 | return false ; |
09 | } |
10 | } catch (e) { |
11 | console.log( 'error:' +str+ '!!!' +e); |
12 | return false ; |
13 | } |
14 | } |
15 | console.log( 'It is not a string!' ) |
16 | } |
1 | var obj = JSON.parse(str) |
2 | typeof obj == 'object' && obj |