Home > database >  How to use jq (or python) to remove a particular key(?) in some JSON?
How to use jq (or python) to remove a particular key(?) in some JSON?

Time:02-10

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?

CodePudding user response:

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)
  • Related