Tech Tip: Verifying If Object Notation Path Exists
PRODUCT: 4D | VERSION: 16R6 | PLATFORM: Mac & Win
Published On: May 4, 2018
It is valid to use object notation with any path as it will compile without error.
For example the following will compile and not show an error until ran:
C_OBJECT(testObj) testObj.sub1.sub2:="Value" |
A way to check if the path exists and contains relevent data is to perform a comparison to Null.
C_OBJECT(testObj) If (testObj.sub1.sub2=Null) //Non-Existant Path or Valid Path containing Null Value End if |
However, a valid path can exist but not contain any values for example:
C_OBJECT(testObj) testObj:=New object testObj.sub1:=New object If (testObj.sub1.sub2=Null) // If condition is entered testObj.sub1.sub2:="Value" End if |
Below is a Utility Method to confirm if a path exists using JSON Validate. It does require each portion of the path to be added as a parameter, but it will not return a false positive on a path that contains a null value:
C_OBJECT($1;$vObj) C_TEXT(${2}) C_BOOLEAN($0) C_OBJECT($vMainSchem) C_OBJECT($vModSchem) C_OBJECT($vSubSchem) C_OBJECT($resObj) C_POINTER($ptSchem) C_LONGINT($i) If (Count parameters>1) $vObj:=$1 $vMainSchem:=New object $vModSchem:=New object $vMainSchem:=$vModSchem $ptSchem:=->$vMainSchem For ($i;2;Count parameters) $ptSchem->type:="object" $ptSchem->required:=New collection $ptSchem->required[0]:=${$i} If ($i<Count parameters) $vSubSchem:=New object $ptSchem->properties:=New object $ptSchem->properties[${$i}]:=$vSubSchem $vModSchem:=$vSubSchem $ptSchem:=->$vModSchem End if End for $resObj:=JSON Validate($vObj;$vMainSchem) $0:=$resObj.success End if |
Below is an example of using the method compared to checking with Null:
C_OBJECT(testObj1) testObj1:=New object $resUtil_1:=OB_PathExist (testObj1;"sub1") $resNull_1:=testObj1.sub1=Null C_OBJECT(testObj2) testObj2:=New object("sub1";Null) $resUtil_2:=OB_PathExist (testObj2;"sub1") $resNull_2:=testObj2.sub1=Null TRACE |