Check if there is a key in the/json array

Asked

Viewed 1,306 times

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 to check if json has the key Autenticacao?

2 answers

1

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

  • Wrong. The function json_decode converts JSON to an object, instance of stdClass, by default. To convert to a array associative the second function parameter should be true: json_decode($json, true).

1


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

Check 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

Check 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

Validation of data from POST

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

Value Returned

Value of the requested variable if successful, FALSE if the filter fails, or NULL if the variable_name parameter 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 be done with only one 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) { ...
  • It worked, but I’m having these mistakes Warning: array_key_exists() expects parameter 2 to be array, null given in it occurs on the line array_key_exists('Autenticacao', $jsonData). I noticed that it occurs when the INPUT_POST this empty, I have to check if I received a Json, know how to do it?

  • I’ll add this info @Hugoborges

  • @Hugoborges added the information.

  • Okay it worked out here, thank you very much.

Browser other questions tagged

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