alone
alone

Reputation: 179

jq extract data of json

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")

Upvotes: 1

Views: 306

Answers (2)

Philippe
Philippe

Reputation: 26727

Using string interpolation :

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

Upvotes: 1

ikegami
ikegami

Reputation: 386541

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.

Upvotes: 2

Related Questions