0

I have a json object. I need to get the values after decoding the json object.

However, some values are blank at times. This brings an error to the way I am fetching.

Kindly see below and advice.

$json = '{
 "Customers": {
 "IdentityStrings": [
 {
 "UniqueSystemIdentifier": "202000000000007004",
 "MSISDN": "211920494162",
 "FirstName": "Donald",
 "MiddleName": {
 },
 "LastName": "Twesiga",
 "DateOfBirth": "2000-01-01",
 "DateIdentityActivated": "20170816153810",
 "DateIdentityRegistered": "20170816153448",
 "OperatorNameRegisteredBy": {
 },
 }
 ]
 },
}';

To get the values, I json decode and fetch as below.

$jsonData = json_decode($json);
 foreach ($jsonData->Customers->IdentityStrings[0] as $key => $value) {
 $UniqueSystemIdentifier = ($jsonData->Customers->IdentityStrings[0]->UniqueSystemIdentifier);
 $MSISDN = ($jsonData->Customers->IdentityStrings[0]->MSISDN);
 $FirstName = ($jsonData->Customers->IdentityStrings[0]->FirstName);
 $MiddleName = ($jsonData->Customers->IdentityStrings[0]->MiddleName);
 $LastName = $jsonData->Customers->IdentityStrings[0]->LastName;
 $DateOfBirth = $jsonData->Customers->IdentityStrings[0]->DateOfBirth;
 $OperatorNameRegisteredBy = $jsonData->Customers->IdentityStrings[0]->OperatorNameRegisteredBy;
 }

The problem comes when some are empty like in this case MiddleName and OperatorNameRegisteredBy.

How can I fetch in case they have values or not?

Thank you.

asked Dec 5, 2017 at 12:09
2
  • 1
    your json is invalid. when in doubt, paste it at jsonlint.com . Commented Dec 5, 2017 at 12:10
  • @YvesLeBorg I think he only pasted partial Json, and forgot to remove the trailing commas. Commented Dec 5, 2017 at 12:18

1 Answer 1

2

Use ternary conditions so that you can get rid of the error;

$MSISDN = (isset($jsonData->Customers->IdentityStrings[0]->MSISDN) && !empty($jsonData->Customers->IdentityStrings[0]->MSISDN))? $jsonData->Customers->IdentityStrings[0]->MSISDN : "";

So the same for all the values.

answered Dec 5, 2017 at 12:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.