判断是否字符串是否是JSON

很多PHPER在开发中数据交互时用的JSON格式,但是没有做很严格的校验,比如一个串是否是正确的json而直接json_decode($str,true),

个人建议在decode前做下校验,防止因为bom头导致json解析失败而引起程序警告:

/**
	 * 判断是否字符串是否是JSON
	 *
	 * @param type $string        	
	 * @param type $datas        	
	 * @author RTS 2015年8月3日16:32:23
	 * @return boolean
	 */
	public static function isJson($string, $datas = array()) {
		$datas = json_decode ( $string, true );
		if (json_last_error () == JSON_ERROR_NONE) {
			return $datas;
		}
		return false;
	}

使用:  

$rawBody = urldecode ( Yii::$app->getRequest ()->getRawBody () ); // 处理url_encode;
$data = Fun::isJson ( $rawBody );//判断串是否是正确JSON 正确的返回$data是数组
if ($data === false) {
  return Fun::returnFalse ( 10002 );
}

  

  

原文地址:https://www.cnblogs.com/renren/p/5466075.html