Avoid error retrieving Json field

2

Well I need to make a handling of an error while retrieving a field from a json.

I have the following Json:

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

I'm recovering 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 this php gives the following error:

Notice: Trying to get property of non-object in

What happens on the line:

$obj->autenticacao->login;

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

    
asked by anonymous 14.08.2017 / 18:09

2 answers

2

I suggest that you check whether the element is 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 it is a array and an array has more than one index then return an 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 it is true assign the values to other variables;

if (is_array($json->Autenticacao) && count($json->Autenticacao) === 1) {
    $login = $json->Autenticacao[0]->login;
    $senha = $json->Autenticacao[0]->senha;
    ...
}
    
14.08.2017 / 18:41
2

So you can avoid creating an error like this:

<?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 to go wrong
DEMONSTRATION going well

    
14.08.2017 / 18:45