您的位置:首页 > Web前端 > JavaScript

判断是否字符串是否是JSON

2016-05-06 16:17 1071 查看

很多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 );
}

  

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: