Is there any way to discover an error occurred in json_decode?

Asked

Viewed 353 times

3

Well, PHP has one thing I sometimes consider bad: Some functions launch Warning when some error occurs, and already others, return False or Null.

A case that exemplifies this is the fopen.

fopen('non-exists.txt', 'r');

Generates a Warning:

PHP Warning: fopen(non-exists.txt): failed to open stream: No such file or directory

But there are other cases where there is no error warning, as in the case of functions json_decode and json_encode.

A small example when trying to decode a poorly formed json:

 json_decode('{'); // null

I need in this case to know that the string JSON is badly formed, because sometimes this JSON comes from external sources, and I think it would be interesting to understand why some operation was wrong, and not only return Null.

Is there any way to find out what is the error occurred in these functions of Json of PHP?

I mean, I’m not talking about making a if and know if there is an error, but I’m talking about detailing what was the problem occurred when trying to use the function.

  • The answer given here will help those who had problems here: http://answall.com/questions/21334/json-retorna-null-com-specialcharacteristics?rq=1

1 answer

3


To detect an invalid or badly formatted json use the function json_last_error_msg() for a description of the problem’s 'category'. This function is available in php5.5 or higher.

$arr = json_decode('{') or die(json_last_error_msg()); //Syntax error

The above code is just one example, the die() can be exchanged for an if.

In previous versions you can use example:

$arr = json_decode('{') ?: json_last_error();//4 representa o erro de sintaxe.
  • Great, you gave the right answer... The problem is, if you have json_decode('false') will cause the or fall into error..

  • +1 guy, thanks a lot..

  • It seems that this function only works for versions 5.5>= of PHP :(

  • @Wallacemaxters yes, but there’s another way to get the description, through the return code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.