php A method for determining whether it is in json format

  • 2021-01-14 05:45:54
  • OfStack

The first thing to remember is that json_encode returns a string, while json_decode returns an object

The data is not in JSON format:


function is_not_json($str){ 
    return is_null(json_decode($str));
}

json: (PHP version greater than 5.3)


function is_json($string) { www.ofstack.com
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

The json_last_error() function returns an error that occurred during the data encoding and decoding process

Note: The string operated on by json codec must be UTF8

example


/**
* parsing json string
* @param type $json_str
* @return type
*/
function analyJson($json_str) {
$json_str = str_replace(' \ \ ', '', $json_str);
$out_arr = array();
preg_match('/{.*}/', $json_str, $out_arr);
if (!empty($out_arr)) {
$result = json_decode($out_arr[0], TRUE);
} else {
return FALSE;
}
return $result;
}

Return false if it is not json

PS: About json operation, here again for you to recommend a few more practical json online tools for your reference:

Online JSON code inspection, inspection, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON online formatting tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON conversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautifying/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json Compression/Escape Tool:

http://tools.ofstack.com/code/json_yasuo_trans

C language style /HTML/CSS/json code formatting beautification tools:
http://tools.ofstack.com/code/ccode_html_css_json


Related articles: