From 9bcbcbc7c09c48d270e2aefe9231836fa61898c4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 5 Oct 2023 12:50:39 -0500 Subject: [PATCH] Add Turn A List From A Command Into JSON as a jq TIL --- README.md | 3 +- jq/turn-a-list-from-a-command-into-json.md | 32 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 jq/turn-a-list-from-a-command-into-json.md diff --git a/README.md b/README.md index 785ce9e..cb4ca7e 100644 --- a/README.md +++ b/README.md @@ -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). -_1340 TILs and counting..._ +_1341 TILs and counting..._ --- @@ -500,6 +500,7 @@ _1340 TILs and counting..._ - [Find All Objects With A Matching Key Value Pair](jq/find-all-objects-with-a-matching-key-value-pair.md) - [Get The First Item For Every Top-Level Key](jq/get-the-first-item-for-every-top-level-key.md) - [Reduce Object To Just Entries Of A Specific Type](jq/reduce-object-to-just-entries-of-a-specific-type.md) +- [Turn A List From A Command Into JSON](jq/turn-a-list-from-a-command-into-json.md) ### Kitty diff --git a/jq/turn-a-list-from-a-command-into-json.md b/jq/turn-a-list-from-a-command-into-json.md new file mode 100644 index 0000000..dd144a0 --- /dev/null +++ b/jq/turn-a-list-from-a-command-into-json.md @@ -0,0 +1,32 @@ +# Turn A List From A Command Into JSON + +There are a lot of command-line utilities that produce a list of things. Since +JSON is a universal data format, it would be useful to be able to quickly turn +some items from `stdout` into a JSON list. + +The [`jq`](https://jqlang.github.io/jq/) utility can help with this. + +Let's say I'm working with the following `git` command that lists changed files +in a specific directory. + +```bash +$ git diff --name-only | grep some/dir +``` + +I can then pipe that list of files to `jq` with a few flags. + +```bash +$ git diff --name-only \ + | grep some/dir \ + | jq -R -s 'split("\n")[:-1]' +``` + +Here's what is going on: + +- The `-R` flag tells `jq` to accept raw input, rather than looking for JSON. +- The `-s` flag is short for `--slurp` and tells `jq` to read in the entire + input before applying the filter. +- The string argument is the filter to be applied to the output. It splits on + newlines and then takes the entire array except for the last item (`[:-1]`) + which would be an empty string for the trailing newline. +- `jq` automatically turns the whole thing into a formatted JSON list.