在PHP json_decode()中检测到错误的json数据?
通过json_decode()解析时,我正在尝试处理错误的json数据。 我正在使用以下脚本:
if(!json_decode($_POST)) {
echo "bad json data!";
exit;
}
如果$ _POST等于:
'{ bar: "baz" }'
然后,json_decode会正确处理错误并吐出“错误的json数据!”;但是,如果我将$ _POST设置为“无效数据”之类的东西,它将给我:
Warning: json_decode() expects parameter 1 to be string, array given in C:\server\www\myserver.dev\public_html\rivrUI\public_home\index.php on line 6
bad json data!
我是否需要编写一个自定义脚本来检测有效的json数据,还是有其他一些漂亮的方法来检测此数据?
soren.qvist asked 2020-06-22T14:37:21Z
7个解决方案
95 votes
以下是有关json_last_error的几件事情:
它返回数据,或在出现错误时返回json_last_error
如果没有错误:当JSON字符串包含null时,它也可以返回json_last_error
它会在有警告的地方发出警告-您要使其消失的警告。
为了解决警告问题,一种解决方案是使用json_last_error运算符(我不经常建议使用它,因为它会使调试更加困难...但是在这里,没有太多选择):
$_POST = array(
'bad data'
);
$data = @json_decode($_POST);
然后,您必须测试json_last_error是否为null-并且要避免json_decode在JSON字符串中为null返回null的情况,可以检查json_last_error,该(引用):
返回上一个错误(如果有) 发生在上一次JSON解析中。
这意味着您必须使用以下代码:
if ($data === null
&& json_last_error() !== JSON_ERROR_NONE) {
echo "incorrect data";
}
Pascal MARTIN answered 2020-06-22T14:38:06Z
17 votes
您还可以使用json_last_error:[http://php.net/manual/en/function.json-last-error.php]
作为文档说:
返回上一个JSON期间发生的最后一个错误(如果有) 编码/解码。
这是一个例子
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
Doua Beri answered 2020-06-22T14:38:39Z
6 votes
这是Guzzle处理json的方式
/**
* Parse the JSON response body and return an array
*
* @return array|string|int|bool|float
* @throws RuntimeException if the response body is not in JSON format
*/
public function json()
{
$data = json_decode((string) $this->body, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error());
}
return $data === null ? array() : $data;
}
Harry Bosh answered 2020-06-22T14:38:59Z
3 votes
我只是因为似乎是完美的json的json语法错误而大失所望:来自URL编码字符串的html_entity_decode($string)。
但是在我的情况下,上述某些内容是html编码的,因为添加html_entity_decode($string)可以达到目的。
$ft = json_decode(html_entity_decode(urldecode(filter_input(INPUT_GET, 'ft', FILTER_SANITIZE_STRING))));
希望这可以节省其他人的时间。
Klompenrunner answered 2020-06-22T14:39:29Z
2 votes
从PHP 7.3开始,json_decode函数将接受新的JSON_THROW_ON_ERROR选项,该选项将使json_decode引发异常,而不是在出错时返回null。
例:
try {
json_decode("{", false, 512, JSON_THROW_ON_ERROR);
}
catch (\JsonException $exception) {
echo $exception->getMessage(); // displays "Syntax error"
}
dtar answered 2020-06-22T14:39:53Z
1 votes
/**
*
* custom json_decode
* handle json_decode errors
*
* @param type $json_text
* @return type
*/
public static function custom_json_decode($json_text) {
$decoded_array = json_decode($json_text, TRUE);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return array(
"status" => 0,
"value" => $decoded_array
);
case JSON_ERROR_DEPTH:
return array(
"status" => 1,
"value" => 'Maximum stack depth exceeded'
);
case JSON_ERROR_STATE_MISMATCH:
return array(
"status" => 1,
"value" => 'Underflow or the modes mismatch'
);
case JSON_ERROR_CTRL_CHAR:
return array(
"status" => 1,
"value" => 'Unexpected control character found'
);
case JSON_ERROR_SYNTAX:
return array(
"status" => 1,
"value" => 'Syntax error, malformed JSON'
);
case JSON_ERROR_UTF8:
return array(
"status" => 1,
"value" => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
default:
return array(
"status" => 1,
"value" => 'Unknown error'
);
}
}
Zakaria.dem answered 2020-06-22T14:40:09Z
-1 votes
我只花了一个小时来浏览本页上所有可能的解决方案。 我将所有这些可能的解决方案的全部自由都集中到一个函数中,以使其更快,更轻松地进行尝试和调试。
我希望它可以对其他人有用。
/**
* Decontaminate text
*
* Primary sources:
* - https://stackoverflow.com/questions/17219916/json-decode-returns-json-error-syntax-but-online-formatter-says-the-json-is-ok
* - https://stackoverflow.com/questions/2348152/detect-bad-json-data-in-php-json-decode
*/
function decontaminate_text(
$text,
$remove_tags = true,
$remove_line_breaks = true,
$remove_BOM = true,
$ensure_utf8_encoding = true,
$ensure_quotes_are_properly_displayed = true,
$decode_html_entities = true
){
if ( '' != $text && is_string( $text ) ) {
$text = preg_replace( '@]*?>.*?\\1>@si', '', $text );
$text = str_replace(']]>', ']]>', $text);
if( $remove_tags ){
// Which tags to allow (none!)
// $text = strip_tags($text, '
,,,');
$text = strip_tags($text, '');
}
if( $remove_line_breaks ){
$text = preg_replace('/[\r\n\t ]+/', ' ', $text);
$text = trim( $text );
}
if( $remove_BOM ){
// Source: https://stackoverflow.com/a/31594983/1766219
if( 0 === strpos( bin2hex( $text ), 'efbbbf' ) ){
$text = substr( $text, 3 );
}
}
if( $ensure_utf8_encoding ){
// Check if UTF8-encoding
if( utf8_encode( utf8_decode( $text ) ) != $text ){
$text = mb_convert_encoding( $text, 'utf-8', 'utf-8' );
}
}
if( $ensure_quotes_are_properly_displayed ){
$text = str_replace('"', '"', $text);
}
if( $decode_html_entities ){
$text = html_entity_decode( $text );
}
/**
* Other things to try
* - the chr-function: https://stackoverflow.com/a/20845642/1766219
* - stripslashes (THIS ONE BROKE MY JSON DECODING, AFTER IT STARTED WORKING, THOUGH): https://stackoverflow.com/a/28540745/1766219
* - This (improved?) JSON-decoder didn't help me, but it sure looks fancy: https://stackoverflow.com/a/43694325/1766219
*/
}
return $text;
}
// Example use
$text = decontaminate_text( $text );
// $text = decontaminate_text( $text, false ); // Debug attempt 1
// $text = decontaminate_text( $text, false, false ); // Debug attempt 2
// $text = decontaminate_text( $text, false, false, false ); // Debug attempt 3
$decoded_text = json_decode( $text, true );
echo json_last_error_msg() . ' - ' . json_last_error();
?>
我将在这里维护它:[https://github.com/zethodderskov/decontaminate-text-in-php/blob/master/decontaminate-text-preparing-it-for-json-decode.php]
Zeth answered 2020-06-22T14:40:38Z