Is there any way to find out an error occurred in json_decode?

3

Well, PHP has something I sometimes find bad: Some functions throw Warning when some error occurs, and others return False or Null .

A case that exemplifies this is 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 malformed json:

 json_decode('{'); // null

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

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

I mean, I'm not talking about making a if and knowing if it has an error, but I'm talking about detailing what the problem was when trying to use the function.

    
asked by anonymous 26.04.2016 / 18:34

1 answer

3

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

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

The code above is just an example, die() can be changed by an if.

In previous versions you can use example:

$arr = json_decode('{') ?: json_last_error();//4 representa o erro de sintaxe.
    
26.04.2016 / 19:08