Skip to content

Commit 12178cf

Browse files
committed
Add Count Each Collection In A JSON Object as a jq TIL
1 parent f731321 commit 12178cf

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1287 TILs and counting..._
13+
_1288 TILs and counting..._
1414

1515
---
1616

@@ -485,6 +485,7 @@ _1287 TILs and counting..._
485485

486486
### jq
487487

488+
- [Count Each Collection In A JSON Object](jq/count-each-collection-in-a-json-object.md)
488489
- [Count The Number Of Things In A JSON File](jq/count-the-number-of-things-in-a-json-file.md)
489490
- [Extract A List Of Values](jq/extract-a-list-of-values.md)
490491
- [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Count Each Collection In A JSON Object
2+
3+
Let's say your JSON file is an object that represents several different
4+
collections (arrays) of data.
5+
6+
```json
7+
{
8+
"users": [ ... ],
9+
"orders": [ ... ],
10+
"carts": [ ... ]
11+
}
12+
```
13+
14+
We can get a nice summary of the counts of those collections using
15+
[`jq`](https://stedolan.github.io/jq/). We can do that with the [`with_entries`
16+
function](https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries).
17+
We preserve the key (name) of each collection and then process each list with
18+
the `length` function.
19+
20+
```bash
21+
jq '. | with_entries({ "key": .key, "value": (.value | length)})' data.json
22+
{
23+
"users": 1234,
24+
"orders": 5432,
25+
"carts": 89
26+
}
27+
```
28+
29+
The `with_entries` function essentially maps over each key-value pair
30+
processing it with the given expression. It will then convert that `{"key":
31+
some_key, "value": 123}` mapping back into a key-value pair that gets combined
32+
with all the others.
33+
34+
[source](https://til.simonwillison.net/jq/flatten-nested-json-objects-jq)

0 commit comments

Comments
 (0)