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

Add Reduce Object To Just Entries Of A Specific Type as a jq TIL

This commit is contained in:
jbranchaud
2023-01-10 14:28:55 -06:00
parent e80721bb6f
commit 93d5e69f97
2 changed files with 30 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).
_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

View File

@@ -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
```