控制台命令结果转json
jq:
So, here's what I did.
I used the command jq
to parse the result of ip route list table all
using a regex, transforming the output to JSON.
Feel free to play around with jq
, and click here to use an online sandbox already loaded with this solution.
ip route list table all | jq --raw-input --slurp 'split("\n") | map(capture("^(?:(?<broadcast>broadcast) ?)?(?:(?<local>local) ?)?(?:(?<multicast>multicast) ?)?(?: ?(?<network>.*?) )(?:from (?<from>\\S+) ?)?(?:via (?<via>\\S+) ?)?(?:dev (?<dev>\\S+) ?)?(?:table (?<table>\\S+) ?)?(?:proto (?<proto>\\S+) ?)?(?:scope (?<scope>\\S+) ?)?(?:src (?<src>\\S+) ?)?(?:metric (?<metric>\\d+) ?)?(?<linkdown>linkdown)?(?<unresolved>unresolved)?"; "g"))'
ip route list type unicast table all|grep -v local|grep -v table|jq --raw-input --slurp 'split("\n") | map(capture("^(?: ?(?<network>.*?) )(?:from (?<from>\\S+) ?)?(?:via (?<via>\\S+) ?)?(?:dev (?<dev>\\S+) ?)?(?:src (?<src>\\S+) ?)?"; "g"))'
ip route list type unicast table all|grep -v local|grep -v table|jq -R -s -c 'split("\n") | map(capture("^(?: ?(?<network>.*?) )(?:from (?<from>\\S+) ?)?(?:via (?<via>\\S+) ?)?(?:dev (?<dev>\\S+) ?)?(?:src (?<src>\\S+) ?)?"; "g"))'
jc: