小鱼儿博客

js判断字符串是否为JSON格式

如果JSON.parse能够转换成功;并且转换后的类型为object 且不等于 null,那么这个字符串就是JSON格式的字符串。

function isJSON(str) {  
	if (typeof str == 'string') {  
		try {  
			var obj=JSON.parse(str);  
			if(typeof obj == 'object' && obj ){  
				return true;  
			} 
		} catch(e) {  
			console.log('error:'+str+'!!!'+e);  
		}
		return false;  
	}
	  
	console.log('It is not a string!') 
}

0

用户头像
  
博客所属
博主:liuzz | 小鱼儿
个人: 属鼠 水瓶座
故乡:河北 秦皇岛
现居:中国 北京
职业:IT码农
主页:http://www.liuzz.com
喜欢: 看海、台球
我的简历:My Resume
联系博主
369264776
jun-yuhong#163.com
说点什么 ×