Check if there is a field inside Json

1

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

$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 nome field? Example:

$json = '{
 "operacao": {

 }
}';
    
asked by anonymous 11.09.2017 / 19:27

3 answers

4

You can use isset :

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

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

    // O valor existe

}
    
11.09.2017 / 19:30
6

You can use the isset function, however there is a however if the value assigned 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

Notice that the property exists but the result was negative. This is because the isset function 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.

    
11.09.2017 / 19:47
1

You can also pass the second parameter of json_decode to true , decoding its JSON to% associative% and use array to check if there is array_key_exists 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)
    
11.09.2017 / 20:41