Skip to content

Commit 9bcbcbc

Browse files
committed
Add Turn A List From A Command Into JSON as a jq TIL
1 parent a726b2e commit 9bcbcbc

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-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-
_1340 TILs and counting..._
13+
_1341 TILs and counting..._
1414

1515
---
1616

@@ -500,6 +500,7 @@ _1340 TILs and counting..._
500500
- [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md)
501501
- [Get The First Item For Every Top-Level Key](jq/get-the-first-item-for-every-top-level-key.md)
502502
- [Reduce Object To Just Entries Of A Specific Type](jq/reduce-object-to-just-entries-of-a-specific-type.md)
503+
- [Turn A List From A Command Into JSON](jq/turn-a-list-from-a-command-into-json.md)
503504

504505
### Kitty
505506

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Turn A List From A Command Into JSON
2+
3+
There are a lot of command-line utilities that produce a list of things. Since
4+
JSON is a universal data format, it would be useful to be able to quickly turn
5+
some items from `stdout` into a JSON list.
6+
7+
The [`jq`](https://jqlang.github.io/jq/) utility can help with this.
8+
9+
Let's say I'm working with the following `git` command that lists changed files
10+
in a specific directory.
11+
12+
```bash
13+
$ git diff --name-only | grep some/dir
14+
```
15+
16+
I can then pipe that list of files to `jq` with a few flags.
17+
18+
```bash
19+
$ git diff --name-only \
20+
| grep some/dir \
21+
| jq -R -s 'split("\n")[:-1]'
22+
```
23+
24+
Here's what is going on:
25+
26+
- The `-R` flag tells `jq` to accept raw input, rather than looking for JSON.
27+
- The `-s` flag is short for `--slurp` and tells `jq` to read in the entire
28+
input before applying the filter.
29+
- The string argument is the filter to be applied to the output. It splits on
30+
newlines and then takes the entire array except for the last item (`[:-1]`)
31+
which would be an empty string for the trailing newline.
32+
- `jq` automatically turns the whole thing into a formatted JSON list.

0 commit comments

Comments
 (0)