Heim  >  Artikel  >  Backend-Entwicklung  >  php如何判断是否为json数据(格式)_PHP教程

php如何判断是否为json数据(格式)_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:36:38949Durchsuche

首先要记住json_encode返回的是字符串, 而json_decode返回的是对象.

判断数据不是JSON格式:

 代码如下
function is_not_json($str){  
    return is_null(json_decode($str));
}


判断数据是合法的json数据: (PHP版本大于5.3)

 代码如下
function is_json($string) { www.111cn.net
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

json_last_error()函数返回数据编解码过程中发生的错误.

注意: json编解码所操作字符串必须是UTF8的.

例子

 

* 解析json串
* @param type $json_str
* @return type
*/
function analyJson($json_str) {
$json_str = str_replace('\\', '', $json_str);
$out_arr = array();
preg_match('/{.*}/', $json_str, $out_arr);
if (!empty($out_arr)) {
$result = json_decode($out_arr[0], TRUE);
} else {
return FALSE;
}
return $result;
}
 代码如下


如果不是json则返回false

  你可能感兴趣的文章
  • php json_encode utf-8中文问题
  • PHP json_encode 中文处理类实例
  • php中GBK/GB2312页面使用json_decode()中文丢失了解决方法
  • PHP5.5 安装后出现不能调用json_encode 解决办法
  • php 通过curl post发送json数据实例
  • php json与数组互转支持中文
  • PHP的json_encode使用分析说明
  • php中json_encode格式中文问题解决方法
  • PHP JSON数据处理实例程序用法
  • PHP JSON数据的创建和解析程序代码

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/738511.htmlTechArticle首先要记住json_encode返回的是字符串, 而json_decode返回的是对象. 判断数据不是JSON格式: 代码如下 function is_not_json($str){ return is_null(json_decode...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn