1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-05 08:08:02 +00:00

Add Filter Out Results Based On List Of Values as a jq TIL

This commit is contained in:
jbranchaud
2023-11-27 17:46:42 -06:00
parent 778555636e
commit 5bcd67946c
2 changed files with 36 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1349 TILs and counting..._
_1350 TILs and counting..._
---
@@ -499,6 +499,7 @@ _1349 TILs and counting..._
- [Count Each Collection In A JSON Object](jq/count-each-collection-in-a-json-object.md)
- [Count The Number Of Things In A JSON File](jq/count-the-number-of-things-in-a-json-file.md)
- [Extract A List Of Values](jq/extract-a-list-of-values.md)
- [Filter Out Results Based On List Of Values](jq/filter-out-results-based-on-list-of-values.md)
- [Find All Objects In An Array Where Key Is Set](jq/find-all-objects-in-an-array-where-key-is-set.md)
- [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md)
- [Get The First Item For Every Top-Level Key](jq/get-the-first-item-for-every-top-level-key.md)

View File

@@ -0,0 +1,34 @@
# Filter Out Results Based On List Of Values
Let's say we have an array of objects in a JSON file. We want to extract some
data about each of those objects, but first we want to filter out some of the
objects that we don't need. This will be based on a list of IDs.
The JSON might look something like this:
```json
[
{'id': '123', ...},
{'id': '456', ...},
{'id': '789', ...},
{'id': '963', ...},
...
]
```
With the [`select`](https://jqlang.github.io/jq/manual/#select) function, we
can filter the array down to those objects whose IDs are
[`not`](https://jqlang.github.io/jq/manual/#and-or-not)
[`inside`](https://jqlang.github.io/jq/manual/#inside) the list of IDs to
exclude.
```
jq '.[] | select([.id] | inside["456", "963"] | not)' data.json
```
Inside that `select`, we grab the `id` as a single value array, check if that
value is inside our _exclude_ array, and then invert that result. If there is a
match, that object will be filtered out.
We can then chain additional filtering and extraction on to the end of the
query to produce the result we want.