jq: Remove keys with empty string values

为君一笑 提交于 2021-01-28 10:28:27

问题


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?


回答1:


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




回答2:


Delete all lines which ends with "":

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


来源:https://stackoverflow.com/questions/63635682/jq-remove-keys-with-empty-string-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!