JSON - is key defined?
I am running into an issue where a JSON response is missing keys...
{
"count": 0,
"pageInformation": {
"offset": 0,
"size": 10
},
"items": []
}Within the JSON response I am only looking for two fields portalUrl and portalId. I have tried using $LENGTH and %IsDefined to check if they are valued but neither work.
If ((tHttpResponseIsObject) && ($ZCONVERT(tHttpResponseContentType,"L") [ "application/json"))
{
set responseData = {}.%FromJSON(tHTTPResponse.Data)
set pResponse = ##class(osuwmc.COM.Response.StringResponse).%New()
if%IsDefined(responseData.items.%Get(0).portalUrl) {
set pResponse.COMPortalURL = responseData.items.%Get(0).portalUrl
} else {
set pResponse.COMPortalURL = ""
}
if%IsDefined(responseData.items.%Get(0).pureId) {
set pResponse.COMPureID = responseData.items.%Get(0).pureId
} else {
set pResponse.COMPureID = ""
}
}Can anyone tell me how I can check to see if a key exists within a JSON response?
Comments
If you're expecting those keys to be defined in the first element of the "items" array like the example code, you can do this:
If responseData.items.%GetTypeOf(0) = "object" {
Set pResponse.COMPortalURL = responseData.items.%Get(0).portalUrl
}This assumes that "items" will always be present and be an array. It checks if the first element of "items" is a nested object, and then sets the target object property to the value of portalUrl in the nested "items" object. You don't need to check if portalUrl is defined since referencing an unassigned key in a %DynamicObject will return the empty string instead of <UNDEFINED>.
We can use the %IsDefined method to check the key is defined, and %Size() to determine the number of the elements in an Object or Array. These methods help to prevent from the <INVALID OREF> and <UNDEFINED>
// verify the "items" is present and it has valuesIf responseData.%IsDefined("items")&&(responseData.items.%Size()) {
Set item1 = responseData.items.%Get(0)
If$IsObject(item1) {
Write item1.portalUrl
}
/*another*/If$IsObject(item1)&&(item1.%IsDefined("portalUrl")) {
Write item1.portalUrl
}
}
The %GetTypeOf method is used to determine the type of a key, and it returns 'unassigned' if the key does not exist
If responseData.%GetTypeOf("items")="array" {
Set item1 = responseData.items.%Get(0)
If$IsObject(item1) {
Write item1.portalUrl
}
}