Check if there is a field inside Json

Asked

Viewed 1,676 times

1

Well I know how to recover a field inside a Json, I do so:

$json = '{
 "operacao": {
    "nome": "hugo"
 }
}';


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


echo $obj->operacao->nome;

But how can I check if json is missing the field nome? Example:

$json = '{
 "operacao": {

 }
}';
  • 3

    if(isset($obj->operacao->nome)){ ... }?

  • 1

    It worked, thank you.

3 answers

6

You can use the function isset, however there is one however if the assigned value is null:

<?php 
$json = '{
    "operacao": {
    "nome": "João"
 }
}';

$obj = json_decode($json);

if( isset( $obj->operacao->nome ) ){
    echo "Existe a propriedade";
} else {
    echo "Não existe a propriedade";
}

//resultado: Existe a propriedade

But the property can exist but with a null value, for example:

$json = '{
     "operacao": {
     "nome": null
   }
}';

//resultado: Não existe a propriedade

Note that the property exists but the result was negative. This is because the function isset determines whether the variable has been defined and is not null.

In this case use the function property_exists:

if( property_exists( $obj->operacao, 'nome' ) ){
    echo "Existe a propriedade";
} else {
    echo "Não existe a propriedade";
}

//resultado: Existe a propriedade

In the case of the function property_exists is checked only if the property exists and the value assigned is not considered.

3


You can use the isset:

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

if(isset($obj->operacao->nome)) {

    // O valor existe

}
  • It worked, thank you.

  • It will be a problem if the value of $obj->operacao->nome is equal to null, the result of the operation isset will be false even though the property exists.

  • It’s true @Filipemoraes, thanks for the explanation! + 1

1

You can also pass the second parameter of json_decode as true, decoding your JSON in a array associative and use array_key_exists to check if there is a key name:

$json = '{
 "operacao": {
    "nome": "hugo"
 }
}';

$obj = json_decode($json, true);

var_dump(array_key_exists('nome', $obj['operacao']));
// Resulta em bool(true) ou bool(false)

Browser other questions tagged

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