Check if there is a key in the / json array

0

Well I have the following json:

{
"Autenticacao": [{
    "login": "teste",
    "token": "100",
    "senha": "123"
}]
}

I get this Json like this:

// Recebe JSON
$json = filter_input(INPUT_POST, 'json', FILTER_DEFAULT);

// Decodifica json
$jsonObj = json_decode($json);

How do you check if json has the key Autenticacao ?

    
asked by anonymous 09.08.2017 / 15:12

2 answers

1

You can use the array_key_exist function but for this you need to inform the json_decode to convert json to array and not objeto , or use the function property_exists to test objeto .

Verify with objeto :

$raw = '{"Autenticacao": [{"login": "teste","token": "100","senha": "123"}]}';

$jsonData = json_decode($raw); 
// Segundo parametro define que a conversão sera para array

var_dump(property_exists($jsonData, 'Autenticacao'));
// Saida: true

Verify with conversion to array :

$raw = '{"Autenticacao": [{"login": "teste","token": "100","senha": "123"}]}';

$jsonData = json_decode($raw, true); 
// Segundo parametro define que a conversão sera para array

var_dump(array_key_exists('Autenticacao', $jsonData));
// Saida: true

Data validation from POST

According to the documentation , the function filter_input will have the following return;

  

Returned

     

Value of the requested variable on success, FALSE if the filter fails, or NULL if the parameter variable_name is an undefined variable. If the FILTER_NULL_ON_FAILURE flag is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Knowing said validation can only be done with a if

// $json = filter_input(INPUT_POST, 'json', FILTER_DEFAULT);
// o filtro FILTER_DEFAULT já é aplicado por padrão então ele pode ser removido
$json = filter_input(INPUT_POST, 'json', FILTER_NULL_ON_FAILURE);
// A variavel $json contera o valor da variavel ou NULL/FALSE em caso de erro.

if ($json) { ...
    
09.08.2017 / 15:21
1

When you make a $jsonObj = json_decode($json) , PHP already turns $ json into an array, so you can do a simple logic test like if(isset($jsonObj['Autenticacao']))

    
09.08.2017 / 15:18