mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Reduce Object To Just Entries Of A Specific Type as a jq TIL
This commit is contained in:
@@ -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).
|
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
|
### jq
|
||||||
|
|
||||||
- [Extract A List Of Values](jq/extract-a-list-of-values.md)
|
- [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
|
### Kitty
|
||||||
|
|
||||||
|
|||||||
28
jq/reduce-object-to-just-entries-of-a-specific-type.md
Normal file
28
jq/reduce-object-to-just-entries-of-a-specific-type.md
Normal 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
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user