Page 1 of 1

convert string to a map

Posted: Thu Jun 25, 2020 6:26 am
by colin
Hi guys, is it possible to ocnvert a string to map? for example
:local arrElements "a=1,b=2,c=3"
:local arr4 [:toarray $arrElements]
:foreach k2,v2 in=$arr4 do={
    :log info "$k2=$v2"
}
Expected output´╝Ü
a=1
b=2
c=3

Actual output:
0=a=1
1=b=2
2=c=3

If define like this, it works:
:local arr5 {d=1; e=2; f=3}
:foreach k2,v2 in=$arr5 do={
    :log info "$k2=$v2"
}
But sometimes we need read the array elements at runtime(for example:from a file).

I know we can implement it like this:
:local equalPosition
:local mapKey
:local mapVal
:foreach e in=$arr4 do={
    :set equalPosition [:find $e "=" 0]
    :set mapKey [:pick $e 0 $equalPosition]
    :set mapVal [:pick $e ($equalPosition + 1) [:len $e]]
    :log info "$mapKey=$mapVal"
}
bu i want to know is there a built in way to implement it.
Thank you.

Re: convert string to a map

Posted: Sat Jul 25, 2020 10:53 am
by pepelxl
Another example:
:local arrElements "a=1,b=2,c=3"
:local tmp
:for i from=0 to=([:len $arrElements] - 1) do={
:if ([:pick $arrElements $i] != ",") do={:set $tmp ($tmp.[:pick $arrElements $i])
} else={:set $tmp ($tmp.";")}
}
:local arr4 [[:parse "({$tmp})"]]
:foreach k2,v2 in=$arr4 do={
    :log info "$k2=$v2"
}

Note that this will only work for simple names. Otherwise, in the loop, the names will need to be wrapped in quotes