Home > Software design >  Select objects based on the key in hash using jq
Select objects based on the key in hash using jq

Time:03-03

I'd love to select objects based on the key in the hash, but I want the original object format back. How can I achieve this?

original

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "aaa.com": {
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  },
   "ccc.com": {
    "https": {
      "dest_url": "https://.com"
    }
  }
}

should be

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
}

I tried it with to_entries[] | select (.key == "google.com" or .key == "bbb.com") | [.key, .value] but it eneded like this. I'm sure [.key, .value] part is wrong but I'm stuck on how I can workaround this.

[
  "google.com",
  {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  }
]
[
  "bbb.com",
  {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
]

CodePudding user response:

Use with_entries(…), which is a shortcut to to_entries | map(…) | from_entries, which in turn decomposes the object into an array of key/value representations to_entries, modifies each item within that array map, and converts it back into the original structure from_entries.

jq 'with_entries(select(.key == "google.com" or .key == "bbb.com"))'
{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "http://github.com"
    }
  },
  "bbb.com": {
    "https": {
      "dest_url": "https://microsoft.com"
    }
  }
}

Demo

  • Related