Home > Software design >  jq extract data of json
jq extract data of json

Time:09-16

I have a file containing strings like : [{ "ip": "127.0.0.1", "timestamp": "1631581369", "ports": [ {"port": 80, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 42} ] }]

I tried the following command to get the output

cat output.json | jq -r '.[].ip,.[].ports[].port '

but the lines are seprated:

127.0.0.1
80

need a string like : 127.0.0.1:80

I tried cat output.json | jq -r '.[].ip,.[].ports[].port | join(":")'

But i get error of running this command:

jq: error (at <stdin>:69): Cannot iterate over string ("127.0.0.1")

CodePudding user response:

jq -r '.[] | .ip   ":"   ( .ports[].port | tostring )' output.json

jqplay
jqplay


Using join, it would be

jq -r '.[] | .ip as $ip | .ports[].port as $port | [ $ip, $port ] | join(":")' output.json

jqplay
jqplay


Both of these solutions work with multiple IP addresses and with multiple ports per IP address.

CodePudding user response:

Using string interpolation :

jq -r '.[] | "\(.ip):\(.ports[].port)"' output.json
  • Related