views:

906

answers:

2

Hi there, I'm trying handle bad json data when parsed through json_decode(). I'm using the following script:

if(!json_decode($_POST)) {
  echo "bad json data!";
  exit;
}

If $_POST equals:

'{ bar: "baz" }'

Then json_decode handles the error fine and spits out "bad json data!"; However, if I set $_POST to something like "invalid data", it gives me:

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!

Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?

+4  A: 

Here are a couple of things about json_decode :

  • it returns the data, or null when there is an error
  • it can also return null when there is no error : when the JSON string contains null
  • it raises a warning where there is a warning -- warning that you want to make disappear.


To solve the warning problem, a solution would be to use the @ operator (I don't often recommend using it, as it makes debuging a lot more harder... But here, there is not much of a choice) :

$_POST = array(
    'bad data'
);
$data = @json_decode($_POST);

You'd then have to test if $data is null -- and, to avoid the case in which json_decode returns null for null in the JSON string, you could check json_last_error, which (quoting) :

Returns the last error (if any) occurred by last JSON parsing.


Which means you'd have to use some code like the following :

if ($data === null
    && json_last_error() !== JSON_ERROR_NONE) {
    echo "incorrect data";
}
Pascal MARTIN
Thank you, that seems to work fine
soren.qvist
You're welcome :-) Have fun !
Pascal MARTIN
A: 

The included json functions in php pretty much... suck. They have a lot of issues. Take a look at json.org to find a good library.

Willi
Thanks i'll check it out.
soren.qvist