Get the Zoom link
Cloud Security Office Hours Banner

jq and JMESPath, hands-on

Cloud tools answer in JSON, a text format for nested data, so much of cloud security work is pulling one fact out of a long JSON answer. Two query languages, jq and JMESPath, cover almost all of it. They look alike and share nothing. Learn both properly, including the mistakes that return an empty result instead of an error.

Jump to the walk-through All how-to guides

·

Time: ~90 minutes  ·  Difficulty: Beginner  ·  You need: jq and a terminal. No cloud account: the lab uses a sample file.

Slides: download the PDF or make your own editable copy (copying needs a Google account). The slides are licensed CC BY-NC 4.0.

The two query languages you will use every single day

JSON (JavaScript Object Notation) is a text format for structured data: objects in curly braces pair names with values, arrays (lists) sit in square brackets, and either can nest inside the other. Cloud security work is, mechanically, JSON wrangling, because nearly everything you look at arrives in it. Every CLI (command-line interface, such as the aws command) returns JSON. Every API (application programming interface, the way a program asks a cloud provider for something) returns JSON. IAM policies, the documents that say who may do what, are JSON. CloudTrail events, AWS's log of API calls, are JSON. Terraform plans, Terraform's preview of the changes it is about to make, are JSON, and every scanner you run emits JSON.

Those answers are often long, and the question you have is usually narrow: which users keep having their requests refused, and from where, or which servers are missing a security setting. The bottleneck between "the data exists" and "I know the answer" is almost always a query you could not quite write. A query language is how you write it: a short expression that says which parts of the JSON to keep and how to arrange them.

There are two languages worth knowing, and confusing them is the most common source of wasted time here, because they look similar and share nothing.

jq is a standalone tool that you run in a terminal, and a powerful language in its own right. It streams: a filter, which is what jq calls an expression, takes JSON values in and emits JSON values out, possibly more or fewer than it received. Use it anywhere you have a file or a pipe (the | that feeds one command's output into the next).

JMESPath is a specification, a written definition of a language, with implementations in many programming languages, which is exactly why AWS embedded it. It is what --query means in the AWS CLI and in the Azure CLI. It is a pure projection language, one that only picks out and reshapes parts of its input: one input document, one output value, no streaming.

Google Cloud is the odd one out and uses neither: gcloud, its command-line tool, has its own --filter and --format syntax. Knowing that up front saves you trying JMESPath against gcloud and concluding you have forgotten how to write it.

On this page

  1. How to use this guide
  2. Streams versus single values
  3. Walk-through
  4. Hands-on exercises
  5. Common mistakes
  6. Where next

How to use this guide

Beginner here means new to jq and JMESPath. You should be comfortable typing commands into a terminal, and it helps to have looked inside a JSON file before, though the sample in step 1 is short enough to read in full. Steps 1 to 6 need no cloud account and no AWS knowledge, because they run against that sample file. Step 6 also uses Python 3, and installs the jmespath package into a virtual environment, a private Python for the lab, so nothing is installed system-wide. Steps 7 and 8 run the AWS CLI against a real account. If you have none, read them without running them: their warnings about --query and --output text apply whenever you use the AWS CLI.

Read it in order. The next section, Streams versus single values, explains the idea behind most jq confusion, and its three short commands need only jq. In the walk-through, step 1 makes a folder called ~/jq-lab and writes five CloudTrail-style events into a file there called events.json. Steps 2 to 5 ask questions of that file with jq, each step adding one technique, and step 6 asks the same questions with JMESPath so you can compare the two. The exercises then ask you to write queries yourself, with each answer hidden until you select "Show the answer".

A code block labelled BASH is something to paste into your terminal, and every block has a copy button. The block labelled JMESPATH, in Exercise 2's answer, is an expression to read, not a command. Step 1's block contains a line that starts cat > events.json <<'EOF', which writes every line after it, down to the one that says only EOF, into events.json. Paste the whole block at once, the EOF line included. Step 6 uses the same pattern with python3 - <<'PY', which runs the lines down to PY as a Python program without saving them to a file. The page has no output blocks. The text before a block says what it does, and the text after it says what to look for in the output.

If a command says it cannot open events.json, the terminal is no longer in the ~/jq-lab folder that step 1 made, so run cd ~/jq-lab and try again. If step 6 says No module named 'jmespath', the terminal has left the virtual environment, so run cd ~/jq-lab && . .venv/bin/activate and try again. If a query prints nothing, or an empty list, do what the last of the common mistakes advises: run it again with the filter removed, to see whether the data is there at all.

Streams versus single values

Step 2 asks jq who made each request that AWS refused, identified by ARN (Amazon Resource Name, AWS's unique name for a user, role or other resource), and jq prints three ARNs, each on its own line. Step 6 asks JMESPath the same question and gets back one list holding the same three ARNs. Both answers are right. They differ in shape, and that difference is worth understanding before you start.

Almost every jq confusion traces back to one idea. jq filters produce a stream, not a value. A stream is a run of separate values, one after another. In the commands below, echo prints a tiny JSON object whose key a holds a list of three numbers, and the pipe hands it to jq. .a means "the value under the key a", and .a[] means "each item in it, one at a time".

echo '{"a":[1,2,3]}' | jq '.a'
echo '{"a":[1,2,3]}' | jq '.a[]'
echo '{"a":[1,2,3]}' | jq '[.a[]]'

The first command prints one output, the array [1,2,3]. jq spreads it over five lines to make it readable, but it is still a single value. The second prints three outputs: 1, then 2, then 3. The third collects that stream back into one array, so it prints the same thing as the first.

Those square brackets in the third line are not decoration. Any time a jq expression produces something that looks almost right but repeated, or almost right but unwrapped, the answer is usually a missing pair of collecting brackets. select(), map(), group_by() and friends all become obvious once you know which of them expect a stream and which expect an array. You will meet select() in step 2, and group_by() and map() working on a collected array in step 4.

JMESPath has no equivalent concept. An expression takes one document and returns one JSON value, always. That constraint is why it is safe to embed in a CLI flag and why it is considerably less capable: there is no way to express "emit a line per element" because there are no lines and no emitting. Step 6 shows the single value, and Exercise 2 puts the two shapes side by side.

Walk-through

1. Build the sample data

This is a trimmed CloudTrail-shaped file. Each record is one API call: who made it (userIdentity.arn), what it was (eventName), where it came from (sourceIPAddress), and the error AWS returned (errorCode, which is null, JSON's empty value, when there was no error). Everything below runs against it, so no cloud account and no credentials are needed.

mkdir -p ~/jq-lab && cd ~/jq-lab

cat > events.json <<'EOF'
{"Records":[
 {"eventTime":"2026-08-20T14:03:11Z","eventName":"AssumeRole","errorCode":null,
  "sourceIPAddress":"203.0.113.14",
  "userIdentity":{"type":"IAMUser","arn":"arn:aws:iam::111122223333:user/alice"}},
 {"eventTime":"2026-08-20T14:03:12Z","eventName":"GetObject","errorCode":"AccessDenied",
  "sourceIPAddress":"198.51.100.7",
  "userIdentity":{"type":"IAMUser","arn":"arn:aws:iam::111122223333:user/bob"}},
 {"eventTime":"2026-08-20T14:05:40Z","eventName":"PutBucketPolicy","errorCode":null,
  "sourceIPAddress":"10.0.4.19",
  "userIdentity":{"type":"AssumedRole","arn":"arn:aws:sts::111122223333:assumed-role/deploy/i-123"}},
 {"eventTime":"2026-08-20T14:06:02Z","eventName":"ListBuckets","errorCode":"AccessDenied",
  "sourceIPAddress":"203.0.113.99",
  "userIdentity":{"type":"IAMUser","arn":"arn:aws:iam::111122223333:user/mallory"}},
 {"eventTime":"2026-08-20T14:06:03Z","eventName":"ListBuckets","errorCode":"AccessDenied",
  "sourceIPAddress":"203.0.113.99",
  "userIdentity":{"type":"IAMUser","arn":"arn:aws:iam::111122223333:user/mallory"}}
]}
EOF

2. jq: navigate, then filter

Start by counting the records. .Records picks out the list of records, and length counts it.

jq '.Records | length' events.json

It prints 5. Next, .Records[] streams each record, and select() passes through only the ones where its condition is true and emits nothing for the rest. This command prints the ARN behind each request that AWS refused:

jq '.Records[] | select(.errorCode == "AccessDenied") | .userIdentity.arn' events.json

You get three ARNs, the one for bob once and the one for mallory twice, each wrapped in double quotes because jq prints strings as JSON. Add -r, for raw output, to print strings unquoted, which is what you want the moment the output feeds another command:

jq -r '.Records[] | select(.errorCode == "AccessDenied") | .userIdentity.arn' events.json

select() is the workhorse. Read select(cond) as a gate in the pipe: the value goes through unchanged if cond is true, and vanishes otherwise.

3. jq: build new objects

This command constructs a new object for each record that has an error, and the brackets around the whole filter collect those objects into one array. The keys, when, what, who and from, are yours to name.

jq '[.Records[]
     | select(.errorCode != null)
     | {when: .eventTime, what: .eventName, who: .userIdentity.arn, from: .sourceIPAddress}]' \
   events.json

It prints an array of three objects, one for each refused request. Reshaping at the edge of a pipeline matters more than it looks. A downstream script that consumes {who, what, when} keeps working when AWS adds fields, moves things around, or you switch to a different source of the same facts.

4. jq: group and count

"Who is generating repeated access denials, and from where." This is a real triage question and it is four operators.

jq -r '
  [.Records[] | select(.errorCode != null)]      # collect failures into an array
  | group_by(.userIdentity.arn)                  # array of arrays, one per principal
  | map({arn: .[0].userIdentity.arn, denials: length})
  | sort_by(-.denials)                           # negate to sort descending
  | .[] | "\(.denials)\t\(.arn)"                 # \(...) is string interpolation
' events.json

Note the shape change at each step: stream, array, array of arrays, array of objects, then back to a stream of strings for printing. group_by requires a sorted array and sorts for you, and it hands each group to map as a list, which is why .[0] is how you get at the shared key.

5. jq: emit something another tool can read

@csv quotes the items of an array and joins them with commas, so this command prints each failed request as one line of CSV (comma-separated values). Pair it with -r, or you get a JSON string containing escaped quotes, which no spreadsheet wants.

jq -r '.Records[]
       | select(.errorCode != null)
       | [.eventTime, .eventName, .sourceIPAddress, .userIdentity.arn]
       | @csv' events.json

@tsv, @sh (shell-quoted), @base64, and @uri exist too. @sh is the one that saves you when a value contains a space or a quote. The next command needs none of them: it collects every source IP address, drops the duplicates with unique, which also sorts them, and prints them on one line separated by commas.

jq -r '[.Records[].sourceIPAddress] | unique | join(", ")' events.json

6. JMESPath: the same questions, different language

Everything below works as an AWS CLI --query value. To practise without a cloud account, evaluate against the same file. The first two lines make a virtual environment in ~/jq-lab/.venv and switch the terminal to it, because the Python that Homebrew installs, and the one on current Debian and Ubuntu releases, refuse a plain pip3 install outside one. The third line installs the Python package jmespath, which is the reference implementation of the language, and the rest runs three queries against events.json. On Debian or Ubuntu, if python3 -m venv says ensurepip is not available, install the python3-venv package first.

python3 -m venv .venv
. .venv/bin/activate
pip install jmespath

python3 - <<'PY'
import json, jmespath
doc = json.load(open('events.json'))
print(jmespath.search("Records[?errorCode=='AccessDenied'].userIdentity.arn", doc))
print(jmespath.search("length(Records[?errorCode!=`null`])", doc))
print(jmespath.search(
    "Records[?errorCode!=`null`].{when: eventTime, what: eventName, who: userIdentity.arn}", doc))
PY

Three pieces of syntax carry most of the weight:

Double quotes in JMESPath do not mean what you think. "ListBuckets" is a quoted identifier, that is, a field name, not a string. So [?eventName == "ListBuckets"] compares the event name against the value of a field called ListBuckets, which does not exist, and returns an empty list. No error, no warning, just nothing. Use single quotes for strings, always.

7. Against a real AWS CLI

Finding public S3 buckets takes more than one call, because whether a bucket is public is a setting on each bucket. This first command gets the list you would work through: --query 'Buckets[].Name' keeps only the bucket names, and --output text prints them as plain text separated by tabs. Checking each bucket takes a further call per bucket.

aws s3api list-buckets --query 'Buckets[].Name' --output text

The next one lists EC2 instances that do not enforce IMDSv2, version 2 of the instance metadata service, and prints each one's instance ID and private IP address:

aws ec2 describe-instances \
  --query 'Reservations[].Instances[?MetadataOptions.HttpTokens!=`required`].[InstanceId,PrivateIpAddress]' \
  --output text

The last one prints the instance IDs of your running EC2 instances, and it filters in two different places. --filters works on the server side: AWS returns only the running instances. --query works on the client side: the CLI receives everything AWS sent back and keeps only the instance IDs. Mixing the two up matters, as the box below explains.

aws ec2 describe-instances \
  --filters 'Name=instance-state-name,Values=running' \
  --query 'Reservations[].Instances[].InstanceId'

--query is client-side, and that is a security-relevant fact, not a performance footnote. The API returns every record and the CLI throws away what your query excluded. You are still billed for the calls, your CloudTrail still records that you read everything, and --query grants you nothing and restricts you from nothing. If you need the API itself to return less, that is --filters on the services that support it, and it is a different flag with different syntax.

8. The combination that gets used most

In practice the strongest move is --output json piped into jq, using JMESPath only for the trivial cases, rather than choosing between them. --output text collapses nulls to the string None and flattens nested lists with tabs, so columns silently misalign the moment a field is empty. For anything you intend to parse, take JSON and use jq. This command lists your IAM users, one per line, with each user's name and creation date separated by a tab:

aws iam list-users --output json \
  | jq -r '.Users[] | [.UserName, .CreateDate] | @tsv'

Hands-on exercises

Exercise 1

Using events.json, print one line per distinct source IP address, showing the IP and the number of events from it, most active first.

Show the answer
jq -r '
  [.Records[]]
  | group_by(.sourceIPAddress)
  | map({ip: .[0].sourceIPAddress, n: length})
  | sort_by(-.n)
  | .[] | "\(.n)\t\(.ip)"
' events.json

If you wrote sort_by(.n) | reverse instead, that is also correct, and 203.0.113.99 still comes first with 2 events. Only the three addresses with one event each come out in the opposite order. sort_by keeps tied items in the order it received them, which is the order group_by left them in, sorted as text, and reverse then flips them. sort_by(-.n) is shorter and is the idiom you will see in other people's filters.

If it stopped with an error that starts Cannot index string with string, check whether you dropped the collecting brackets around .Records[]. group_by needs an array. Without the brackets, jq hands it one record at a time, and a record is an object, so group_by works through that record's field values instead. The first of those is the event time, a string, and asking a string for .sourceIPAddress stops jq with that error.

Exercise 2

Translate this jq filter into JMESPath: .Records[] | select(.userIdentity.type == "IAMUser") | .userIdentity.arn. Then say what is different about the output.

Show the answer
Records[?userIdentity.type=='IAMUser'].userIdentity.arn

Note the single quotes. Double quotes would make IAMUser a field name and silently return an empty list.

The output difference is the whole distinction between the two languages. jq emits four separate JSON strings, one per line, which a shell loop can consume directly. JMESPath returns a single JSON array, which is why --query pairs with --output text so often: the CLI has to flatten the array back into lines for you, because the language cannot.

Exercise 3

A colleague reports that this command "returns nothing, so we have no running instances". They are looking at an account with forty running instances. What is wrong?

aws ec2 describe-instances --query 'Reservations[].Instances[?State.Name == "running"].InstanceId'
Show the answer

"running" is a quoted identifier, so the filter compares State.Name against a field named running, finds nothing there, and the comparison is never true. The fix is 'running', and in a shell that means escaping or switching the outer quoting:

aws ec2 describe-instances \
  --query "Reservations[].Instances[?State.Name == 'running'].InstanceId"

Worth sitting with the failure mode rather than just the fix. An empty result and a correct result look identical from the outside, and the reasonable interpretation of "no output" is "no matching resources". Before believing any empty result from a query language, run the query with the filter removed and confirm the data is there at all. Confirm the instrument works before trusting what it says is absent.

Exercise 4

Write a jq filter that finds any IAM policy statement granting "Action": "*", handling the fact that Action may be a string or an array of strings. Test it against both shapes.

Show the answer

The trick is to normalise first. In jq, wrapping a value in an array and flattening it is the idiomatic way to say "make this a list either way". The block below writes a test policy with three statements, one whose Action is the string "*" and two whose Action is an array, and then runs the filter against it.

cat > policy.json <<'EOF'
{"Statement":[
  {"Effect":"Allow","Action":"*","Resource":"*"},
  {"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":"*"},
  {"Effect":"Allow","Action":["iam:*","*"],"Resource":"*"}
]}
EOF

jq -r '.Statement[]
       | select(.Effect == "Allow")
       | select([.Action] | flatten | index("*"))
       | "wildcard action: \(.Action)"' policy.json

It prints two lines: wildcard action: * for the first statement and wildcard action: ["iam:*","*"] for the third. The second statement grants no wildcard, so it does not appear.

[.Action] | flatten turns both a bare string and an array into a flat array, and index("*") returns the position of the first match or null. select() treats null as false, so the statement passes through only when the wildcard is present.

The equivalent normalise-then-compare pattern appears in the Rego page for the same reason: the IAM document schema is polymorphic in several places, and any tool that reads it has to handle both shapes or it will miss findings on whichever shape it did not consider.

Common mistakes

Where next