mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Extract A List Of Values as a jq til
This commit is contained in:
@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||
|
||||
_974 TILs and counting..._
|
||||
_975 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -28,6 +28,7 @@ _974 TILs and counting..._
|
||||
* [HTML](#html)
|
||||
* [Internet](#internet)
|
||||
* [JavaScript](#javascript)
|
||||
* [jq](#jq)
|
||||
* [Linux](#linux)
|
||||
* [Mac](#mac)
|
||||
* [MongoDB](#mongodb)
|
||||
@@ -384,6 +385,10 @@ _974 TILs and counting..._
|
||||
- [Yarn Commands Without The Emojis](javascript/yarn-commands-without-the-emojis.md)
|
||||
- [Yup Schemas Are Validated Asynchronously](javascript/yup-schemas-are-validated-asynchronously.md)
|
||||
|
||||
### jq
|
||||
|
||||
- [Extract A List Of Values](jq/extract-a-list-of-values.md)
|
||||
|
||||
### Linux
|
||||
|
||||
- [Check Ubuntu Version](linux/check-ubuntu-version.md)
|
||||
|
||||
49
jq/extract-a-list-of-values.md
Normal file
49
jq/extract-a-list-of-values.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# Extract A List Of Values
|
||||
|
||||
[`jq`](https://stedolan.github.io/jq/) can be used to extract a list of values
|
||||
from an array in a JSON file.
|
||||
|
||||
Consider the following JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{ "id": 1, "name": "Liz Lemon" },
|
||||
{ "id": 2, "name": "Pete Hornberger" },
|
||||
{ "id": 3, "name": "Tracy Jordan" },
|
||||
{ "id": 4, "name": "Jenna Maroney" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
First, you need to specify the selector path to the list. One it's own that
|
||||
will grab the list.
|
||||
|
||||
```bash
|
||||
$ jq '.items' data.json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Liz Lemon"
|
||||
},
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
Then you need to use brackets to interact with the list. `.items[0]` and
|
||||
`.items[1]` would grab the first and second item in the list, respectively.
|
||||
Leaving the brackets empty (`.items[]`) tells `jq` that you want to interact
|
||||
with each item in the list.
|
||||
|
||||
Then tack on a selector for what you want out of each item.
|
||||
|
||||
```bash
|
||||
$ jq '.items[].name' data.json
|
||||
"Liz Lemon"
|
||||
"Pete Hornberger"
|
||||
"Tracy Jordan"
|
||||
"Jenna Maroney"
|
||||
```
|
||||
|
||||
This grabs the name from each of the objects within the _items_ array. The
|
||||
results are printed to stdout.
|
||||
Reference in New Issue
Block a user