Home > php教程 > php手册 > body text

php检测数据是否为json字符

WBOY
Release: 2016-05-25 16:44:15
Original
1370 people have browsed it

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

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

判断数据不是JSON格式:

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

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

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

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;
}
?>
Copy after login

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

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

});

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


永久链接:

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!