Community discussions

MikroTik App
 
man
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 51
Joined: Tue Jul 25, 2017 2:58 pm

json string to associative array

Tue Jun 19, 2018 2:01 pm

Hello everyone!
Another question regarding parsing json string.
I have a file saved with fetch tool:
test.txt contents:
{"properties":{"trial":"5", "ssid":"Test1", ... }}
or could be simle string:
{"trial":"5", "ssid":"Test1", ... }

Is there a way to parse this string to associative array or variables ...
trial = 5
ssid = Test1
...
 
man
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 51
Joined: Tue Jul 25, 2017 2:58 pm

Re: json string to associative array

Tue Jun 19, 2018 4:51 pm

The simple string like this
{"trial":"5", "ssid":"Doe"}
(i have put this string to variable $jstr )
may be parsed with this code:
{
:global sIndex 0;
:global eIndex [:len $jstr];
:global qChar "\"";
:global asArr ({});
:global oq 0;
:global cq 0;
:global isKey true;
#
#
:do {
	:local tmpCh [:pick $jstr $sIndex ($sIndex +1)];
	:if  ($tmpCh = $qChar) do={
		:set $sIndex ($sIndex +1);
		:set $oq $sIndex;
	}
:global key;
:global val;
	:while ($oq > $cq) do={
			:local tmpCh [:pick $jstr $sIndex ($sIndex +1)];
			:if  ($tmpCh = $qChar) do={
			:set $cq $sIndex;
			:put ("VAR = ".[:pick $jstr $oq $cq]);
			:if ($isKey) do={
				:set $key [:pick $jstr $oq $cq];
				:set $isKey false;
			} else={
				:set $val [:pick $jstr $oq $cq];
				:set $isKey true;
				:put ("Key = ".$key." Val=".$val);
				:set ($asArr->$key) ($val);
			}
		}
		:set $sIndex ($sIndex +1);
	}
:set $eIndex ($eIndex -1);
:set $sIndex ($sIndex +1);
} while=($eIndex > 0)
:put ($asArr);
}
It is a script whichout any improvements, written in 30minutes. If i will get more free time i will rewrite it

Who is online

Users browsing this forum: No registered users and 23 guests