diff --git a/README.md b/README.md index e3e1053..c3ffd83 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). -_1272 TILs and counting..._ +_1273 TILs and counting..._ --- @@ -478,6 +478,7 @@ _1272 TILs and counting..._ ### jq - [Extract A List Of Values](jq/extract-a-list-of-values.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/reduce-object-to-just-entries-of-a-specific-type.md b/jq/reduce-object-to-just-entries-of-a-specific-type.md new file mode 100644 index 0000000..f0d0547 --- /dev/null +++ b/jq/reduce-object-to-just-entries-of-a-specific-type.md @@ -0,0 +1,28 @@ +# Reduce Object To Just Entries Of A Specific Type + +Let's say I have a large JSON data file with a ton of top-level fields of +varying types. It can be hard to wade through it as is. [The `jq` +utility](https://stedolan.github.io/jq/manual/) can help. I can filter a JSON +object down to just the fields of a certain type. + +For instance, I may want to start with a view of the JSON that is restricted to +just the values of type `array`. + +To do this, I need to use a couple different `jq` helper functions. + +```bash +jq '. | to_entries | map(select(.value | type | match("array"))) | from_entries' data.json +``` + +This starts with `to_entries` to convert an object into an array of key-value +pairs. I then `map` over those pairs selecting just the pairs whose value +matches the `"array"` type. I then use `from_entries` to turn the reduced array +back into an object. + +There is a less verbose way to do the above. The `to_entries` and +`from_entries` can be collapsed into a `with_entries` that wraps the `map` +call. + +```bash +jq '. | with_entries(map(select(.value | type | match("array")))' data.json +```