Page 1 of 1
Hash hb_HGetDef()
Posted: Thu Nov 04, 2021 10:25 am
by vagblad
Hello all,
We've been using hb_HGetDef() to retrieve values from a hash array and its ok for 1st tier values. How can we retrieve values which are on a 2nd level?
For example [data][id]. The [data] node has 2 keys inside it: id and name.
If i do it like this
Code: Select all
hTest :=hb_HGetDef( tempHash , "data", "" )
it returns back another Hash containing [id] and [name].
After that i can run this:
Code: Select all
hTest2 :=hb_HGetDef( hTest , "name", "" )
and this will give me the value i want. i was wondering it there is a way to do it in 1 line of code instead of 2 like i am doing it right now.
thanks in advance
Re: Hash hb_HGetDef()
Posted: Thu Nov 04, 2021 12:28 pm
by edk
Hi Vagelis.
Try out my code:
Code: Select all
cData_Name := HashsGet ( tempHash , { "data", "name" }, "" )
*******************************************************************************
Function HashsGet ( xVal, aKeys, xDefault )
/* function for retrieving key values from nested json / Hash structures
json / Hash structure example:
{ "orders" => {
"buyer" => {
"personalData" =>
{ "firstName" => "Jan" ,
"lastName" => "Kowalski" } ,
"address" =>
{ "city" => "Łódź",
"street" => "Piotrkowska" }
} ,
"items" => {
"id" => "123-456-789" ,
"EAN" => "5901234567096",
"description" => Nil
}
}
}
xVal is a Hash variable from which we want to read the key value.
aKeys is an array with nested keys, e.g. when we want to read the value of a key
"orders" => "buyer" => "address" => "city" we declare:
aKeys := { "orders", "buyer", "address", "city" }
xDefault is an optional value to be returned by the function,
if the structure given in aKeys does not exist or the key value read is Nil
or xVal is not of Hash type.
*/
IF hb_IsString ( aKeys )
aKeys := { aKeys }
ENDIF
AEVAL( aKeys, { |x| IF ( hb_IsHash( xVal ) .AND. hb_HHasKey( xVal, x ), ;
xVal := hb_HGet( xVal, x ), ;
xVal := xDefault ) } )
IF xVal = Nil
RETURN xDefault
ENDIF
RETURN xVal
Re: Hash hb_HGetDef()
Posted: Thu Nov 04, 2021 12:54 pm
by vagblad
edk wrote: ↑Thu Nov 04, 2021 12:28 pm
Hi Vagelis.
Try out my code:
Hi Edward,
it works perfectly.
Simple, elegant, brilliant.
Thank you once more.