Community discussions

MikroTik App
 
colin
newbie
Topic Author
Posts: 46
Joined: Mon May 11, 2015 11:11 am

convert string to a map

Thu Jun 25, 2020 6:26 am

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.
 
pepelxl
just joined
Posts: 20
Joined: Tue Jul 23, 2013 6:59 pm

Re: convert string to a map

Sat Jul 25, 2020 10:53 am

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

Who is online

Users browsing this forum: smartcoda and 13 guests