Ad

How To Use Jq (or Python) To Remove A Particular Key(?) In Some JSON?

- 1 answer

Here is the input json. It is a partial JSON dump of a puppet class extracted from Red Hat Satellite.

{
  "Id": 9999,
  "Match": "fqdn=server.fqdn.com",
  "Value": {
    "user1": {
      "order": 90,
      "nofile": {
        "comment": "I want to lose this comment",
        "soft": "65535",
        "hard": "65535"
      },
      "nproc": {
        "comment": "I want to lose this also",
        "soft": "32768",
        "hard": "32768"
      }
      },
    "user2": {
      "order": 90,
      "nofile": {
        "comment": "I want to lose this comment",
        "soft": "65535",
        "hard": "65535"
      },
      "nproc": {
        "comment": "I want to lose this also",
        "soft": "32768",
        "hard": "32768"
      }
    }
  }
}

I want to delete all the "comment"s. I can't find an example that does this, or an explanation of something that does this in general. Or I am too stupid to understand what I have read so far.

So my output would be

{
  "Id": 9999,
  "Match": "fqdn=server.fqdn.com",
  "Value": {
    "user1": {
      "order": 90,
      "nofile": {
        "soft": "65535",
        "hard": "65535"
      },
      "nproc": {
        "soft": "32768",
        "hard": "32768"
      }
      },
    "user2": {
      "order": 90,
      "nofile": {
        "soft": "65535",
        "hard": "65535"
      },
      "nproc": {
        "soft": "32768",
        "hard": "32768"
      }
    }
  }
}

Any takers?

Ad

Answer

del( .. | objects | .comment )

Demo on jqplay


In Python, it would look something like this:

def remove_comments(node):
   if isinstance(node, dict):
      if 'comment' in node:
         del node['comment']
      for child in node.values():
         remove_comments(child)
   elif isinstance(node, list):
      for child in node:
         remove_comments(child)
Ad
source: stackoverflow.com
Ad