Skip to content

Start Here: Writing Inline Expressions

Hello, jq

The simplest jq command merely echoes its input. It looks like this:

Terminal window
cat input.json | jq '.'

I read the jq program '.' as “print this”, but what’s “this”? By default, jq labels the content it receives from the stdin stream as “this”.

When you run this command, jq prints a nicely-formatted version of the JSON object it receives from stdin to stdout.

Terminal window
echo '{"a": 1, "b": 2, "c": {"d": 4, "e": 5}}' | jq '.'
{
"a": 1,
"b": 2,
"c": {
"d": 4,
"e": 5
}
}

Excellent!

Filters

Now you can learn about some elementary filters, such as how to select objects within objects, values with objects, and items within arrays. Maybe you can guess what an expression like .c.e does…

Terminal window
echo '{"a": 1, "b": 2, "c": {"d": 4, "e": 5}}' | jq '.c.e'
5

…or maybe you prefer to know that .c.e is shorthand for .c | .e, which illustrates how . (“this”) behaves. The output of the preceding filter becomes . (“this”) in the following filter. Moreover, jq uses | to connect filters together, just like piping works in bash and its cousins.

echo '{"a": 1, "b": 2, "c": {"d": 4, "e": 5}}' | jq '.c | .d'
4

And you can select objects as well as atomic values.

echo '{"a": 1, "b": 2, "c": {"d": 4, "e": 5}}' | jq '.c'
{
"d": 4,
"e": 5
}

That’s Enough!

You have literally all you need to write jq code to transform JSON values into other JSON values. You can go very far with just this bit of knowledge and some haphazard reading of the jq manual.

You’re ready for the next step when you start to struggle to understand complicated expressions or you want to remove duplication from those expressions.