Parse data (ip adress) from a text file and from JSON.

There is such a site: wtfismyip.com, where you can conveniently get the address in a text file or json. I don’t know much about Linux (RouterOS is Linux after all) and I can’t figure out how to parse the IP address that this site gives out.
I found an example of saving the address to a file.

/tool fetch url="https://wtfismyip.com/text" mode=https dst-path=ip.txt
local ip [file get ip.txt contents ]
:put $ip

But I would not like to write something to the Mikrotik disk. I would like to immediately get a ready-made ip.
Moreover, I would like to have two options: from text and from json.

:local ip ([/tool fetch url="https://wtfismyip.com/text" output=user as-value]->"data")

This output contains blanks, you can find script to strip it or you can use ipify.org which doesn’t contains blanks in output text:

:local ip ([/tool fetch url="https://api.ipify.org" output=user as-value]->"data")

or you can get from JSON from wtfismyip.com without blanks but you need parser script like: https://github.com/Winand/mikrotik-json-parser.

Thank you, I was just planning to start working on scripts again closer to the New Year, and in particular parsing json. Now I will know what to focus on.

Special thanks for this site and code. Before this, I could not find a site where the address is obtained separately (in a file, in json, or something else)

Now Mikrotik has a built-in function for deserializing JSON. But I can’t parse the answer. Can you show an example of how to do this for the JSON format for this example https://api.ipify.org?format=json?

For example, I tried to do this:

:put [:deserialize [[/tool fetch url="https://api.ipify.org?format=json"] contents] from=json]                   
  status: failed
failure: resolving error

or

:put ([:deserialize [[/tool fetch url="https://api.ipify.org?format=json"] contents] from=json]->"ip")
  status: failed
failure: resolving error

or

:put [:deserialize [[/tool fetch url="http://api.ipify.org?format=json"] contents] from=json]         
  status: failed
failure: resolving error

It seems to be an access error, possibly a DNS error. Although the old method works:

:put [([/tool fetch url="https://api.ipify.org" output=user as-value]->"data")]

I’ll answer myself. It worked. Here are a couple of examples

:local result [/tool fetch url="https://api.ipify.org/?format=json" mode=https output=user as-value]
:local respdata [:deserialize from=json ($result->"data")]
:local ip ($respdata->"ip")
:put $ip

and

:local result [/tool fetch url="https://api.ipify.org/?format=json" mode=https output=user as-value]
:local ip "Not available"
:do {
    :if (($result->"status") = "finished") do={
        :local respdata [:deserialize from=json ($result->"data")]
        :set ip ($respdata->"ip")
    } else={
        :put "Fetch error: status not finished"
    }
} on-error={
    :put "Error deserializing JSON"
}
:put $ip
1 Like