PHP method to determine whether json format is correct

小云云
Release: 2023-03-22 12:00:01
Original
3937 people have browsed it


本文主要和大家分享php判断json格式是否正确的方法,主要以代码的方式和大家分享,希望能帮助到大家。

1、校验json格式是否有误:

function data($value) {
    $res = json_decode($value, true);    
    $error = json_last_error();    
    if (!empty($error)) {        echo "<pre class="brush:php;toolbar:false">";
        print_r($value);        echo "
Copy after login
"; } return $res; }

延伸:json_last_error可以判断返回 JSON 编码解码时最后发生的错误。 错误如下:有对应的数字编码,但是只要非空,就表示有错误,对于一般的json格式校验来说,已经足够了!
PHP method to determine whether json format is correct

0 = JSON_ERROR_NONE No error has occurred

1 = JSON_ERROR_DEPTH The maximum stack depth has been exceeded

2 = JSON_ERROR_STATE_MISMATCH Invalid or malformed JSON

3 = JSON_ERROR_CTRL_CHAR Control character error, possibly incorrectly encoded

4 = JSON_ERROR_SYNTAX Syntax error

5 = JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded PHP 5.3.3

人性化的输出json错误!

<?php
     if (!function_exists(&#39;json_last_error_msg&#39;)) {         function json_last_error_msg() {
             static $ERRORS = array(
                 JSON_ERROR_NONE => &#39;No error&#39;,
                 JSON_ERROR_DEPTH => &#39;Maximum stack depth exceeded&#39;,
                 JSON_ERROR_STATE_MISMATCH => &#39;State mismatch (invalid or malformed JSON)&#39;,
                 JSON_ERROR_CTRL_CHAR => &#39;Control character error, possibly incorrectly encoded&#39;,
                 JSON_ERROR_SYNTAX => &#39;Syntax error&#39;,
                 JSON_ERROR_UTF8 => &#39;Malformed UTF-8 characters, possibly incorrectly encoded&#39;
             );             $error = json_last_error();             return isset($ERRORS[$error]) ? $ERRORS[$error] : &#39;Unknown error&#39;;
         }
     }
Copy after login

2、带中文字的数组转json方法一(推荐)

加参数:JSON_UNESCAPED_UNICODE

$array = array(&#39;key&#39; => &#39;value&#39;, &#39;test&#39; => array(&#39;测试一下&#39;, 2, 3));echo "<pre class="brush:php;toolbar:false">";
print_r(json_encode($array, JSON_UNESCAPED_UNICODE));echo "
Copy after login
";exit;

PHP method to determine whether json format is correct

3、另一种方法将带中文字的数组转json方法:

//将汉字,特殊字符原样变成json数据function ch_json_encode($data) {
    $ret = ch_urlencode($data);    $ret = json_encode($ret);    return &#39;\&#39;&#39; . addslashes(urldecode($ret)) . &#39;\&#39;&#39;;
}//汉字,特殊字符变可读懂的字符串主程序function ch_urlencode($data) {
    if (is_array($data) || is_object($data)) {        foreach ($data as $k => $v) {            if (is_scalar($v)) {                if (is_array($data)) {                    $data[$k] = urlencode($v);
                } else if (is_object($data)) {                    $data->$k = urlencode($v);
                }
            } else if (is_array($data)) {                $data[$k] = ch_urlencode($v); // 递归调用该函数
            } else if (is_object($data)) {                $data->$k = ch_urlencode($v);
            }
        }
    }    return $data;
}
Copy after login

php5.2以后自带json_decode函数,但是对json文本串的格式要求非常严格。

很可能使用该函数得到的返回值是NULL,没有返回数组只有可能要么是编码问题,要么就是json返回的数据又特殊字符别无其他原因,下面是解决方法:

可以使用使用json_last_error()函数获取到的返回值来帮助我们判断出问题的原因。

其中如果提示错误JSON_ERROR_SYNTAX(Syntax error),表示json串格式错误。

可以通过以下几个方式排错:

  1. json字符串必须以双引号包含

$output = str_replace("&#39;", &#39;"&#39;, $output);
Copy after login
  1. json字符串必须是utf8编码

$output = iconv(&#39;gbk&#39;, &#39;utf8&#39;, $output);
Copy after login

3.不能有多余的逗号 如:[1,2,],用正则替换掉

preg_replace(&#39;/,\s*([\]}])/m&#39;, &#39;$1&#39;, $output)
Copy after login

4、不能有换行、制表符:这个非常坑,经常排除了所有的错误还是出不来,就是这个地方,多了个换行符啥的,尤其是在excel编辑之后再导入到数据库,然后再用php取出的时候!

$jsonstr = &#39;

{"succ":true,"data":{"id":"31","keywords":"","description":"","jianjie":"       ","jianjie_short":"bb","nav":"ccc","deleted":"0","url":"http:\/\/travel.sina.com.cn\/beijing\/

"}}&#39;;//$ret=preg_replace("/\t/", " ", $ret);  

//$jsonstr = preg_replace("/\n/", &#39; &#39;, $jsonstr);$jsonstr = str_replace("\n", &#39; &#39;, $jsonstr);//print_r($jsonstr);exit;//$jsonstr = str_replace (&#39;\n&#39;,&#39;&#39;, $jsonstr);$jd = json_decode($jsonstr,true);$errorinfo = json_last_error();//print_r(JSON_ERROR_DEPTH);

print_r($jd);
Copy after login

当对UTF-8编码的文件进行操作时,如果要把读取的内容当作文本内容来处理,最好先对BOM进行一些处理,这个问题在PHP6中得到了解决(可以设置文本/二进制读取模式),有兴趣的朋友可以自己查找PHP6的手册。

相关推荐:

PHP如何判断json格式是否正确

The above is the detailed content of PHP method to determine whether json format is correct. For more information, please follow other related articles on the PHP Chinese website!

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 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!