跳到主要內容

判斷是不是json格式 - PHP



<?php

/**
 * Check the string is json
 * 
 * @param string $str
 * @return bool
 * @throws Exception if the string is not json
 */
function isJson($str) {
    json_decode($str);

    $code = json_last_error();
    switch ($code) {
        case JSON_ERROR_NONE:
            return true;
        case JSON_ERROR_DEPTH:
            throw new Exception("Maximum stack depth exceeded");
        case JSON_ERROR_STATE_MISMATCH:
            throw new Exception("Underflow or the modes mismatch");
        case JSON_ERROR_CTRL_CHAR:
            throw new Exception("Unexpected control character found");
        case JSON_ERROR_SYNTAX:
            throw new Exception("Syntax error, malformed JSON");
        case JSON_ERROR_UTF8:
            throw new Exception("Malformed UTF-8 characters, possibly incorrectly encoded");
        default:
            throw new Exception("Unknown error");
    }
}

$str = "Test";
$response = isJson($str);
?>

寫了一個可以判斷json錯誤的情況,當然也可以有個簡單版,如下



<?php

/**
 * Check the string is json
 * 
 * @param string $str
 * @return bool
 */
function isJsonSimple($str) {
    json_decode($str);
    return json_last_error() == JSON_ERROR_NONE;
}

$str = "Test";
$response = isJsonSimple($str);
?>

但這些前提是,PHP環境必須是5.3.0以上哦,因為使用到json_last_error

留言

這個網誌中的熱門文章

What is phpize

What is phpize According to the PHP official document : The phpize command is used to prepare the build environment for a PHP extension. If you need to build such an extension that from github or another code repositories, you can use  build tools to perform the build manually.