Heim  >  Artikel  >  php教程  >  php检测数据是否为json字符

php检测数据是否为json字符

WBOY
WBOYOriginal
2016-05-25 16:44:151371Durchsuche

检测返回的数据是不是json格式的数据我们可以使用几个方法来判断,下面我整理了一些比较实用的检测json字符串是不是json格式的例子,希望例子能帮助各位带来帮助哦。

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

判断数据不是JSON格式:

<?php
function is_not_json($str) {
    return is_null(json_decode($str));
}
?>

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

<?php
function is_json($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}
?>

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

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

如果不是json则返回false

<?php
/**
 * 解析json串
 * @param type $json_str
 * @return type
 */
private function analyJson($json_str) {
    $json_str = str_replace(&#39;\\&#39;, &#39;&#39;, $json_str);
    $out_arr = array();
    preg_match(&#39;/\{.*\}/&#39;, $json_str, $out_arr);
    if (!empty($out_arr)) {
        $result = json_decode($out_arr[0], TRUE);
    } else {
        return FALSE;
    }
    return $result;
}
?>

上面的几种方法都可以检测来是不是json数据,当然我还有一个另类的做法就是使用ajax来实现,例子如下使用AJAX请求来获得JSON数据,并输出结果:代码如下复制代码$ . getJSON("test.js", function (json) {

    alert("JSON Data: " + json . users[3] . name);

});

如果返回的值不正确就是不合法的json字符串了,是不是这样也可以呀。


永久链接:

转载随意!带上文章地址吧。

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