首先要记住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.jb51.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

PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com