From 0ec717b64cbd9009c90fc5793af7bfe02b036365 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 3 May 2023 16:14:08 -0500 Subject: [PATCH] Add Get The First Item For Every Top-Level Key as a jq TIL --- README.md | 3 +- ...-the-first-item-for-every-top-level-key.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 jq/get-the-first-item-for-every-top-level-key.md diff --git a/README.md b/README.md index 11eb4c6..a8fbd52 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). -_1298 TILs and counting..._ +_1299 TILs and counting..._ --- @@ -490,6 +490,7 @@ _1298 TILs and counting..._ - [Extract A List Of Values](jq/extract-a-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) - [Reduce Object To Just Entries Of A Specific Type](jq/reduce-object-to-just-entries-of-a-specific-type.md) ### Kitty diff --git a/jq/get-the-first-item-for-every-top-level-key.md b/jq/get-the-first-item-for-every-top-level-key.md new file mode 100644 index 0000000..7c36f79 --- /dev/null +++ b/jq/get-the-first-item-for-every-top-level-key.md @@ -0,0 +1,37 @@ +# Get The First Item For Every Top-Level Key + +Let's say we have a JSON object where each key in that object is tied to a +large array of values. To get a better idea of what the data looks like, we +want to trim down the JSON a bit. Essentially, we want to tie each key to the +first value in each of their respective arrays. + +We can do this by reducing the object into a new object where each top-level +key is tied to the first item in its array. + +```bash +$ jq '. as $object | reduce keys[] as $k ({}; .[$k] = $object[$k][0])' data.json +``` + +This uses variables (`$object` and `$k`) and the [`reduce` +function](https://stedolan.github.io/jq/manual/#Reduce) to iterate over the +incoming JSON object and produce a new object with the trimmed down data. + +JSON like this: + +```json +{ + "key1": ["a", "b", "c"], + "key2": [1, 2, 3], + "key3": ["x", "y", "z"] +} +``` + +will be turned into this: + +```json +{ + "key1": "a", + "key2": 1, + "key3": "x" +} +```