Home > Software engineering >  jq - return true when key is not present
jq - return true when key is not present

Time:06-08

I have a test that uses jq results and returns "true" when a key name does not exist in my json and false when it does

Specifically I have JSON like this ( first example)

{
  "control": "library_blacklist",
  "policy_id": 13,
  "policy_name": "the-policy"
}

However when a blacklisted library is found then the output looks like this (second example)

{
  "blacklisted_library_found": [
    "library.dll"
  ],
  "control": "library_blacklist",
  "failed": true,
  "policy_id": 13,
  "policy_name": "the-policy"
}

So I need a jq query that will resolve to true in the first example where key "blacklisted_library_found" is not present and false in the second example where key blacklisted_library_found is present

CodePudding user response:

Use has to check for the presence of that key, in combination with not to invert the result:

jq 'has("blacklisted_library_found") | not'

This produces true for the first example, and false for the second. Demo

  • Related