在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

php json语法错误,在PHP json_decode()中检测到错误的json数据?相关推荐

  1. 终端服务器安全层在协议流中检测到错误,并已取消客户端连接。客户端IP:x.x.x.解决方法

    终端服务器安全层在协议流中检测到错误,并已取消客户端连接.客户端IP:x.x.x.解决方法 事件类型: 错误 事件来源: TermDD 描述: RDP 的 "DATA ENCRYPTION& ...

  2. php中常见的错误类型有,JavaScript中常见的错误类型有哪些?(详细介绍)

    在JavaScript中,当发生错误时会生成描述错误类型的错误对象,此错误对象包含错误类型和编号等信息,这些信息可用于后续处理等,在本篇文章中将给大家介绍常见的错误类型以及如何处理这些错误. Java ...

  3. python语言包含的错误,Python语言程序中包含的错误,一般分为三种,以下____________不是其中的一种...

    Python语言程序中包含的错误,一般分为三种,以下____________不是其中的一种 答:编译错误 人体体温能自动调控在37度,其原因是( ). 答:人体内产生的热能是分批放出的 人体内有完善的 ...

  4. php 屏蔽mysql错误提示_PHP.ini中配置屏蔽错误信息显示和保存错误日志

    在PHP程序运行过程中如果有错误发生,在浏览器上是否显示错误信息,以及显示错误信息的级别是我们在程序开发.调试.运营过程中需要控制的. root@(none):/alidata/www/default ...

  5. MVC中提示错误:从客户端中检测到有潜在危险的 Request.Form 值的详细解决方法...

    今天往MVC中加入了一个富文本编辑框,在提交信息的时候报了如下的错误:从客户端(Content="<EM ><STRONG ><U >这是测试这...&q ...

  6. 终端服务器安全层在协议流中检测到错误,终端服务器安全层在协议流中检测到错误,并已取消客户端连接...

    事件类型: 错误 事件来源: TermDD 描述: RDP 的 "DATA ENCRYPTION" 协议组件在协议流中检测到一个错误并且中断了客户机. 经过网上查找资料及分析,原来 ...

  7. 计算机错误符号,解析Excel中常见的错误符号以及解决方法

    解析Excel中常见的错误符号以及解决方法分享给大家, Excel 电子表格是很多人都要使用的软件,也相信很多人都会用,但是用得好不好就差别很大了,用得好的话可以让工作效率大大提高,但关于Excel的 ...

  8. 在系统二进制文件中检测到错误_门禁管理系统施工中常见的布线错误

    现在门禁系统已经深入到人们的生活中,门禁系统安装应用越来越广泛.但是门禁系统施工布线都需要注意哪些你了解吗?下面就门禁系统施工布线过程中的几大错误现象给大家提个醒. 一.用网络线布电锁锁到控制器的线! ...

  9. json日期格式化 java_java_Java Web程序中利用Spring框架返回JSON格式的日期,返回Json时格式化日期Date 第一 - phpStudy...

    Java Web程序中利用Spring框架返回JSON格式的日期 返回Json时格式化日期Date第一步:创建CustomObjectMapper类 /** * 解决SpringMVC使用@Respo ...

最新文章

  1. 【modbus】libmodbus库的移植与使用
  2. egg(113)--egg之登录成功跳转到登录之前的页面
  3. springboot知识
  4. 解决input[type=file]打开时慢、卡顿问题
  5. 服务端第八次上课:mongodb,redis
  6. python2.7安装使用thulac库时遇到的一些问题
  7. 如果世界上只有一种数据结构,那么我选择 hash
  8. 小姐姐:如何参与大型开源项目-Taro 共建
  9. pat 乙级 1015 德才论(C++)
  10. oracle的日志模式,Oracle数据日志模式
  11. 【Golang】基于RSA算法的数据通信和数字签名
  12. docker 下安装oracle
  13. centos7安装打印机 cups页面管理 java程序驱动打印程序
  14. python 求向量模长(一范二范)
  15. 百度提供的LBS服务
  16. C++学习笔记:指向指针的指针
  17. 27个iOS开源库,让你的开发坐上火箭吧
  18. ProGuard的作用
  19. 电源系统ORING工作原理
  20. linux系统实训总结报告,linux实训心得体会范文

热门文章

  1. python语言创意绘画-Python街机模块的draw系列绘画例子集合
  2. Conflux树图生态项目[comupage社区派]获第2届「社造学园奖」“最佳创新”奖
  3. antd vue上传图片至后端
  4. Linux命令常见面试题
  5. 程序员情感三部曲之程序员如何找女朋友
  6. 使用 github pages, 快速部署你的静态网页
  7. windows11备忘录便签快捷键:你需要知道的有关它的一切
  8. 【计算机毕业文章】垃圾分类系统设计与实现
  9. 短信发送平台的推广技巧有哪些?3个小技巧要记牢
  10. Android取消广播的方法名,去除Android中的角标