-2

I have an API endpoint which one of the below JSON responses:

{
    "requestId":"114382-4744950-1",
    "errorCode": "500.002.1001",
    "errorMessage": "Service is currently under maintenance. Please try again later"
}

or

{
    "OriginatorCoversationID": "60682-3118069-1",
    "ResponseCode": "0",
    "ResponseDescription": "success"
}

I need to check if the response had "errorCode" key in the JSON object to respond effectively. How do I check in PHP/Laravel if JSON object has a given key/property?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • 3
    You decode it, and then you check if the resulting object has the property, or the resulting array the key, the normal way. – CBroe Nov 08 '21 at 11:53

2 Answers2

0

I think you can use isset method.

For example

if(isset($jsonData->errorCode){
//your code
}
Gurkan Atik
  • 468
  • 4
  • 10
0

The call would look like this, if you are using guzzle, if you don't you should.

$response = $client->get('http://httpbin.org/headers')->getBody();

Now you will have the response as an array, to avoid index errors, use isset() to check if the key is there.

if (isset($response['errorCode'])) {

}

If you prefer to work with objects, you can convert the array to an object and do the following.

$response = (object) $client->get('http://httpbin.org/headers')->getBody();

if ($response->errorCode) {

} 
mrhn
  • 17,961
  • 4
  • 27
  • 46