Quantcast
Channel: MikroTik
Viewing all articles
Browse latest Browse all 15133

Scripting • Re: Inconsistent results with JSON serialize, deserialize and numbers

$
0
0
There are no floats in RouterOS script, so that there "lost in translation" is to be expected IMO — there is no way to store the floating point number. So it becomes a string, and thus a string if later serialized back to JSON. This is expected behavior IMO since "serialized" has no way to know the variables was originally a floating point. So str type make sense here:
Code:
:put [:typeof ([:deserialize "{\"x\":1.1}" from=json ]->"x")] str

I think it's RouterOS "ip" and "ip-prefix" variable types that make things look wrong... RouterOS script allows pre-CIDR IPv4 addressing so 1.1 are 1.1.1 are both valid IP addresses so if used without quotes they becomes an "ip" type in script — not a floating point. This is just how RouterOS script work, and since JSON does NOT have an IP address type, it comes a string. And essentially ":tostr" is performed on the IP type before serializing into JSON. So this make sense...in the context of how RouterOS script types work that is ;)
Code:
:put [:serialize to=json 1.1.1]                                 "1.1.0.1"              

@rextended, there is the "time" type too, which is handled correctly IMO:
Code:
:put [:serialize to=json [:timestamp]]     "2023-12-28 14:33:04"
but that is also asymmetric, similar to floats (but in reverse), since JSON does NOT have a time type. So "serialized" make the time a ISO-like date as a JSON string. Also seems right to me.

Perhaps more simply, the RouterOS types and JSON types don't perfectly align — so something has to happen.
e.g. RouterOS does not have floats & JSON does not have ip address nor time types.
So...when type mismatch happens... it becomes a string in either serialize/deserialize direction is the basic rule.

Statistics: Posted by Amm0 — Thu Dec 28, 2023 4:56 pm



Viewing all articles
Browse latest Browse all 15133

Trending Articles