Learn `jq` Basics
TODO: collapasable, copyable, download, etc
What are the first things I should learn to be effective at using jq
?To be effective at using jq
, a versatile command-line JSON processor, here are the first things you should learn:
Basic Filtering: Understand how to extract values using
.
for the whole JSON and.fieldname
for specific fields.echo '{"name": "John", "age": 30}' | jq '.name'
Pipes (
|
): Use pipes to process the output of one filter with another.echo '{"people": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}' | jq '.people[] | .name'
Array Indexing: Access elements in an array using indices.
echo '[1, 2, 3, 4]' | jq '.[2]'
Iteration over Arrays (
[]
): Iterating over array elements.echo '{"people": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}' | jq '.people[]'
Select function: Using
select()
for filtering data based on conditions.echo '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]' | jq '.[] | select(.age > 28)'
Map Function: Transforming arrays with
map()
.echo '[1, 2, 3, 4]' | jq 'map(. * 2)'
Length Function: Finding the length of arrays or strings.
echo '[1, 2, 3, 4]' | jq 'length'
Combining Filters: Chain multiple filters to transform and extract data.
echo '{"name": "John", "friends": ["Jane", "Doe"]}' | jq '.name, .friends[]'
Variables in
jq
: Use variables to store intermediate results.echo '{"people": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}' | jq '.people[] | . as $person | $person.name'
String Interpolation: Embed the result of one expression inside a string.
echo '{"name": "John", "age": 30}' | jq '"The name is \(.name) and age is \(.age)"'
Once you grasp these basics, you can delve deeper into more advanced features of jq
such as recursive descent, conditionals, functions, and more. Remember to frequently refer to the jq
manual (man jq
or online documentation) for a comprehensive list of its capabilities and examples.if a field is a string with escaped JSON, how can I parse that string in jq as json?If you have a JSON string that's been escaped and is presented as a string in your input JSON, you can use the fromjson
filter in jq
to parse it.
Here's an example to illustrate:
Given the following JSON:
{
"data": "{\"name\":\"John\",\"age\":30}"
}
The field data
contains an escaped JSON string. To parse the data
field as JSON and then extract, let's say, the name
field, you would use:
echo '{"data": "{\"name\":\"John\",\"age\":30}"}' | jq '.data | fromjson | .name'
The above command would output:
"John"
The fromjson
filter effectively parses the escaped JSON string, converting it back into a JSON object that you can then further process with other jq
filters.
Related Chats
Learn `jq` Basics 0.999
Extract `key` and `value`. 0.424
New chat 0.377
SF Fine Dining Recommendations 0.363
Python Server Streaming JSON 0.351
Modern ES6 Array Filtering 0.330
Dynamic Auto-Complete Component 0.311
Base64 encoded values. 0.300
Convert Objects to Set 0.298