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) { ...
Wrong. The function
json_decode
converts JSON to an object, instance ofstdClass
, by default. To convert to a array associative the second function parameter should betrue
:json_decode($json, true)
.– Woss