Jq: Getting all the values of an array
source link: https://proinsias.github.io/til/jq-getting-all-the-values-of-an-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Francis T. O'Donovan
Data Science Manager at LeanTaaS – Planet discoverer, researcher, developer, geek.
Jq: Getting all the values of an array
May 2, 2023
less than 1 minute read
Assuming you have a json string or file containing an array such as:
{
"response": [
1000,
{
"text": "blabla"
},
{
"text": "blabla2"
},
{
"text": "blabla3"
}
]
}
You can extract the values of the text
field from the array using jq
:
> jq '.response[].text?' file.json
"blabla"
"blabla2"
"blabla3"
Or you can select using the type of each array element using either jq '.response[] | objects | .text' file.json
or jq '.response[] | select(type=="object" and has("text")) | .text' file.json
Finally, you can include a placeholder value for array elements without the text
field of interest:
> jq '.response[] | if type=="object" and has("text") then .text else null end' file.json
"blabla"
"blabla2"
"blabla3"
Via Stack Overflow.
Categories: til
Updated: May 2, 2023
You may also enjoy
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK