File tree 2 files changed +36
-1
lines changed 2 files changed +36
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1287 TILs and counting..._
13
+ _ 1288 TILs and counting..._
14
14
15
15
---
16
16
@@ -485,6 +485,7 @@ _1287 TILs and counting..._
485
485
486
486
### jq
487
487
488
+ - [ Count Each Collection In A JSON Object] ( jq/count-each-collection-in-a-json-object.md )
488
489
- [ Count The Number Of Things In A JSON File] ( jq/count-the-number-of-things-in-a-json-file.md )
489
490
- [ Extract A List Of Values] ( jq/extract-a-list-of-values.md )
490
491
- [ Find All Objects With A Matching Key Value Pair] ( jq/find-all-objects-with-a-matching-key-value-pair.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments