Avoid error while recovering Json field

Asked

Viewed 48 times

2

Good need to do an error handling while retrieving a field from a json.

I have the following Json:

{
    "Autenticacao": {
        "login": "123",
        "senha": "123"
    }
}

I’m retrieving the data like this:

// Decodifica o Json
$obj = json_decode($json);

$obj->autenticacao->login;

So far so good, the problem is when the user informs a json that contains an array, like this:

{
    "Autenticacao": [{
        "login": "123",
        "senha": "123"
    }]
}

With that php gives the following error:

Notice: Trying to get property of non-object in

That occurs on the line:

$obj->autenticacao->login;

How can I treat this error and tell the user that json is not correct.

  • You should have it constant, or you get it one way or the other... Never with that unpredictability. Or is there some reason for it?

  • This is counting, but if someone from the Front-end forget is sending wrong I want to treat the error, avoiding the error in php and the creation of a log.

2 answers

2


I suggest you check to see if the element is or is not a array, but if it is an array it would be ideal to check if there is only one key (if the front-end sends an array with two keys).

$raw = '{"Autenticacao": {"login": "123","senha": "123"}}';
$json = json_decode($raw);

var_dump(is_array($json->Autenticacao) && count($json->Autenticacao) > 1);
// Saida: bool(false)

In the example above, if you are a array and be an array have more than one Dice then return one erro of invalid data.

$raw = '{"Autenticacao": [{"login": "123","senha": "123"}]}';
$json = json_decode($raw);

var_dump(is_array($json->Autenticacao) && count($json->Autenticacao) > 0);
// Saida: bool(true)

In the above example if true assign values to other variables;

if (is_array($json->Autenticacao) && count($json->Autenticacao) === 1) {
    $login = $json->Autenticacao[0]->login;
    $senha = $json->Autenticacao[0]->senha;
    ...
}

2

So you can avoid making a mistake as follows:

<?php
$json = '{
    "Autenticacao": [{
        "login": "123",
        "senha": "123"
    }]
}';

$obj = json_decode($json);
if(!isset($obj->Autenticacao->login)) { // aqui verificamos se a propriedade existe
    die('error brrrhh'); //  erro aqui,usuário informa um json que contenha um array
}
echo $obj->Autenticacao->login; // está tudo bem

DEMONSTRATION going wrong
DEMONSTRATION going well

  • Very good, thank you

Browser other questions tagged

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