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
user6721269
-
1your json is invalid. when in doubt, paste it at jsonlint.com .YvesLeBorg– YvesLeBorg2017年12月05日 12:10:44 +00:00Commented Dec 5, 2017 at 12:10
-
@YvesLeBorg I think he only pasted partial Json, and forgot to remove the trailing commas.mega6382– mega63822017年12月05日 12:18:40 +00:00Commented Dec 5, 2017 at 12:18
1 Answer 1
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
Himanshu Upadhyay
6,5571 gold badge23 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-php