Skip to content
Advertisement

Remove specific data from json file in linux

I have a json file with set of data with repeating fields. I need to remove an entry with specific data of a field.

Json file:

[
    {
        "targets": [
            "172.17.1.199"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1742",
            "__snmp_module__": "arista_sw"
        }
    },
    {
        "targets": [
            "172.17.1.51"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1754",
            "__snmp_module__": "arista_sw"
        }
    }
]

The json file goes on and but this is an example of the whole json file.

I need to remove an entry of targets with its labels given a data of the target's IP.

Input:

172.17.1.51

expected output:

[
    {
        "targets": [
            "172.17.1.199"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1742",
            "__snmp_module__": "arista_sw"
        }
    }
]

Advertisement

Answer

Using jq:

$ jq --arg ip 172.17.1.51 'map(select(.targets | contains([$ip]) | not ))' input.json 
[
  {
    "targets": [
      "172.17.1.199"
    ],
    "labels": {
      "__meta_netbox_pop": "st-1742",
      "__snmp_module__": "arista_sw"
    }
  }
]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement