jq: Remove keys with empty string values

Viewed 620

I have the following JSON:

{
  "data": [
    {
      "{#NAME}": "Test 1",
      "{#ID}": "1",
      "{#IP}": "192.168.1.2:80"
    },
    {
      "{#NAME}": "Test 2",
      "{#ID}": "2",
      "{#IP}": ""
    },
    {
      "{#NAME}": "Test 3",
      "{#ID}": "3",
      "{#IP}": "192.168.1.3:80"
    },
    {
      "{#NAME}": "Test 4",
      "{#ID}": "4",
      "{#IP}": "192.168.1.4:80"
    },
    {
      "{#NAME}": "Test 5",
      "{#ID}": "5",
      "{#IP}": ""
    }
  ]
}

But I want to return:

{
  "data": [
    {
      "{#NAME}": "Test 1",
      "{#ID}": "1",
      "{#IP}": "192.168.1.2"
    },
    {
      "{#NAME}": "Test 2",
      "{#ID}": "2",
    },
    {
      "{#NAME}": "Test 3",
      "{#ID}": "3",
      "{#IP}": "192.168.1.3"
    },
    {
      "{#NAME}": "Test 4",
      "{#ID}": "4",
      "{#IP}": "192.168.1.4"
    },
    {
      "{#NAME}": "Test 5",
      "{#ID}": "5",
    }
  ]
}

I'm very new to using JQ and not sure how I can go about doing this. I read through this issue page on GitHub but none of the example seem to work for me.

I also need to remove the port number and colon. Is that possible?

2 Answers

You can do below, to select values that are not empty using with_entries(expr), with the expr being the condition that excludes the empty fields.

Also use the .value field again to remove the string that matches the regex containing the port string.

jq '.data |= map(with_entries(select(.value != "") | .value |= sub(":[0-9][0-9]$"; "")))'

jqplay - Online demo

Delete all lines which ends with "":

sed -r '/""$/d' test.json
Related