From 5bcd67946c16fe820a5bc9c6a06efa972fb53aeb Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 27 Nov 2023 17:46:42 -0600 Subject: [PATCH] Add Filter Out Results Based On List Of Values as a jq TIL --- README.md | 3 +- ...ter-out-results-based-on-list-of-values.md | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 jq/filter-out-results-based-on-list-of-values.md diff --git a/README.md b/README.md index d97f327..a9c2efa 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/jq/filter-out-results-based-on-list-of-values.md b/jq/filter-out-results-based-on-list-of-values.md new file mode 100644 index 0000000..95d3421 --- /dev/null +++ b/jq/filter-out-results-based-on-list-of-values.md @@ -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.