How to check if json is an object

Asked

Viewed 226 times

0

Well get a json on my page like this:

// Decodifica o Json
$obj = json_decode(file_get_contents('php://input'));

echo $obj->Autenticacao[0]->login;

The Json that is being sent is like this:

{
"Autenticacao": [{
    "login": "root",
    "senha": "123"
}]
}

Everything works 100%, but whoever removes [] from json, php tells me the following error:

Fatal error: Cannot use object of type stdClass as array

How to identify if the full json.

  • If you don’t have [] it is no longer possible to do Autenticacao[0], it would have to be just $obj->Autenticacao->login. is_object can verify if a given field is an object and is_array to see if it’s array.

1 answer

2


So if nay you want an array in the property Authentication, Not you can do this:

echo $obj->Autenticacao[0]->login;

Because you’re trying to access it in the form of array that does not exist should be as follows:

echo $obj->Autenticacao->login;

And to access it that way your json must be something like:

{
    "Autenticacao": {
        "login": "root",
        "senha": "123"
    }
}

Browser other questions tagged

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