PHP 判断 字符串 是JSON

封装is_json函数判断是否JSON,

// is_json('123'); AI回答,未匹配
function is_json($string) {
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

给出比较完美


function is_json($string, $assoc = true){
  //$string可能是数组,对象is_object(),以及资源is_resource();
  if(!is_string($string)){
    return false;
  }
  $data = json_decode($string, $assoc);
  //json_decode未报错,但有可能是整型,浮点型
  if(json_last_error() != JSON_ERROR_NONE || is_int($data) || is_float($data)){
    return false;
  }
  return true;
}

//另外一个版本

function isJson($string = '', $assoc = true){
  if(is_string($string)){
    $data = json_decode($string, $assoc);
    if(($data && is_object($data)) || (is_array($data) && !empty($data))){
      return true;
    }
  }
  return false;
}

//json_validate(); //PHP8增加函数

 


//测试
$arr = array(
  'a' => '{"a":"a1","b":"b1"}',             //是JSON
  'b' => "{\"a\":\"a1\",\"b\":\"b1\"}",     //是JSON
  'c' => '123',                             //不是JSON
  'd' => 123,                               //不是JSON
  'e' => Null,                              //不是JSON
  'f' => false,                             //不是JSON
  'g' => true,                              //不是JSON
  'h' => '\"a\":\"a1\",\"b\":\"b1\"}',      //不是JSON
  'i' => 123456789012345678901234567890,    //不是JSON
  'j' => '123456789012345678901234567890',  //不是JSON
  'k' => '90.123',                          //不是JSON
  'l' => 90.123,                            //不是JSON
  'm' => array('aa' => 'bb'),               //不是JSON
  'n' => array("aaa" => "bbb"),             //不是JSON
  '0' => 1,                                 //不是JSON
  'p' => '1',                               //不是JSON
  'q' => 0,                                 //不是JSON
  'r' => '0',                               //不是JSON
);
foreach($arr as $key => $val){
  if(is_json($val)){
    echo $key . '-' . $val . ' 是JSON<hr>';
  }else{
    echo $key . ' 不是JSON<hr>';
  }
}


$data = new stdClass();
var_dump(is_json($data));                     //不是JSON
echo '<hr>';
$data = fopen('php://stdin', 'r');
var_dump(is_json($data));                     //不是JSON

 

 

posted @ 2024-12-28 18:12  钢锅  阅读(189)  评论(0)    收藏  举报