I cannot find the way to post the data properly using http-data option of fetch command (I know it is only in the RC version still 6.39rc62)
I am trying
tool fetch http-method=post http-data=$myVar url=http://example.com
but I the value is sent as the name of the post variable with an empty value
I want to be able to define in plain format
serial=1231454525
model=rb951 and so on
anyone knows anything that could help?
Use this function:
# convert object to json
# Params
# objectParam
# Returns
# String json representing object
:global toJson do={
:global toJson
:local ret "{"
:local firstIteration true
:foreach k,v in $objectParam do={
if ($firstIteration) do={
:set $ret ($ret . $k . "=")
} else={
:set $ret ($ret . "," . $k . "=")
};
:set $firstIteration false
:local type [:typeof $v]
:if ($type = "array") do={
:set $ret ($ret . [$toJson objectParam=$v])
} else={
:if ($type = "str") do={
:set $ret ($ret . "\"" . $v . "\"")
} else {
:set $ret ($ret . $v )
};
};
};
:set $ret ($ret . "}")
:return $ret;
};
To add on Ricard2k’s function and make it JSON string, write it as follows;
:global toJson do={
:global toJson
:local ret "{"
:local firstIteration true
:foreach k,v in $objectParam do={
if ($firstIteration) do={
:set $ret ($ret . "\"".$k . "\":")
} else={
:set $ret ($ret . "," . "\"". $k . "\":")
};
:set $firstIteration false
:local type [:typeof $v]
:if ($type = "array") do={
:set $ret ($ret . [$toJson objectParam=$v])
} else={
:if ($type = "str") do={
:set $ret ($ret . "\"" . $v . "\"")
} else {
:set $ret ($ret . $v )
};
};
};
:set $ret ($ret . "}")
:return $ret;
};
Then you can use Javascript’s JSON.parse to decode the string to JSON
This is excellent – thank you!
I had some trouble figuring out how to invoke this, so here’s an example for the record:
:local msg ({});
:set ($msg->"cpuLoad") [/system resource get cpu-load];
:set ($msg->"temp") [/system health get temperature];
:set ($msg->"cpuTemp") [/system health get cpu-temperature];
:put [$toJson objectParam=$msg]
Outputs: {“cpuLoad”:1,“cpuTemp”:54,“temp”:47}