3

I have following json

[
   {
      "ip":"105.105.105.105",
      "timestamp":"1543746097",
      "ports":[
         {
            "port":80,
            "proto":"tcp",
            "status":"open",
            "reason":"syn-ack",
            "ttl":128
         }
      ]
   },
   {
      "ip":"105.105.105.105",
      "timestamp":"1543746097",
      "ports":[
         {
            "port":53,
            "proto":"tcp",
            "status":"open",
            "reason":"syn-ack",
            "ttl":128
         }
      ]
   }
]

I want to extract ports to simple csv output

80,53

I tried

jq -r '.[]."ports" | map(.port) | @csv' 105.105.105.105_tcp.json

and

jq -r '.[]."ports" | map(.port) | join(",")' 105.105.105.105_tcp.json

but none of them work.

5

Here's a jq-only solution:

jq -r '[ .[].ports[].port ]|@csv' network.json
80,53

The approach here is to retrieve the port numbers, wrap them into an array, and then convert it to the CSV format.

0

I was able to get desired output by

jq -r '.[]."ports" | .[].port' 105.105.105.105_tcp.json | tr '\n' ',' | sed 's/,*$//g'

However I'm wondering if it can be done in more elegant way.

0
bash $ jtc -w'<port>l+0' -jr input.json | sed s/[][]//g 
 80, 53 
bash $ 

jtc will extract and print all ports and wrap those into the array. sed is needed to drop the arrays encasing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.