Sub topic 6
Scripting with JSON output and jq
This chapter shows how to turn Databricks CLI output into values a shell script can use. It assumes you can run databricks commands against a configured profile (earlier chapters), you know pipes and exit codes in a POSIX shell, and you can read JSON. You do not need prior jq experience.
Why JSON output
By default, many CLI commands print a human-friendly table. Tables are fine to read but fragile to parse, because column widths and headings can change between CLI versions. The --output json flag (short form -o json) prints the API response as JSON instead. JSON has stable field names, so scripts can depend on them.
jq is a command-line JSON processor. It reads JSON on standard input, applies a filter, and prints the result. The usual pattern is:
databricks <group> <command> --output json | jq '<filter>'The working model: three output channels
A command gives your script three separate signals:
- stdout carries the data. Pipe this into jq.
- stderr carries error messages and diagnostics. A pipe does not capture it, so it appears on your terminal unless you redirect it.
- The exit code tells you whether the command succeeded. Zero means success. Non-zero means failure.
Scripts break when they treat these as one stream. Never write 2>&1 before a pipe into jq. An error message mixed into stdout is not valid JSON, and jq will stop with a parse error that hides the real problem.
Start every script with strict mode:
#!/usr/bin/env bash
set -euo pipefail-estops the script when a command fails.-ustops on unset variables.pipefailmakes a pipeline fail when any stage fails. Without it, a faileddatabrickscommand piped into jq reports jq's exit code, which is usually zero.
jq essentials
These filters cover most Databricks scripting.
| Filter | Meaning | Column |
|---|---|---|
| `.field` | Read a field. `.settings.name` reads a nested field. | |
| `.[]` | Emit each element of an array as a separate value. | |
| `.[]?` | Same, but produce nothing (no error) if the input is `null`. | |
| `select(cond)` | Keep only values where the condition is true. | |
| `a // b` | Use `b` when `a` is `null` or `false`. | |
| `[a, b] \ | @tsv` | Format an array as one tab-separated line. |
| `-r` | Print strings raw, without JSON quotes. | |
| `-e` | Set jq's exit code from the last output: non-zero if it was `null` or `false`. | |
| `--arg name value` | Pass a shell value into jq as a string. | |
| `--argjson name value` | Pass a shell value into jq as JSON (numbers, booleans, objects). |
Worked example: list running clusters
#!/usr/bin/env bash
set -euo pipefail
databricks clusters list --output json \
| jq -r '.[]? | select(.state == "RUNNING") | [.cluster_id, .cluster_name] | @tsv'Each output line has the cluster ID, a tab, and the cluster name. Tab-separated lines work well with cut, awk, and read. Names can contain spaces, so a tab is safer than a space as the separator.
The .[]? matters. If a workspace has no clusters, some commands print nothing or null instead of []. Plain .[] would fail on null, while .[]? simply produces no lines.
Looping over results
To act on each result, read jq's output line by line:
#!/usr/bin/env bash
set -euo pipefail
databricks jobs list --output json \
| jq -r '.[]? | select((.settings.name // "") | startswith("nightly_")) | .job_id' \
| while read -r job_id; do
state=$(databricks jobs list-runs --job-id "$job_id" --output json \
| jq -r '.[0].state.result_state // "NONE"')
echo "job ${job_id}: last result ${state}"
donePoints to note:
(.settings.name // "")guards against jobs with no name. Callingstartswithonnullis an error in jq.read -rstops the shell from interpreting backslashes.list-runsreturns runs newest first, so.[0]is the latest run. A job that has never run gives an empty list, and the// "NONE"fallback handles that case.result_stateis only set once a run has finished. A run in progress has alife_cycle_statesuch asRUNNINGbut noresult_state.
Keep in mind that each loop iteration starts another CLI process and makes another API call. For a few dozen jobs this is fine. For thousands, look for a single call that returns the data you need.
Capturing a single value
Use command substitution for one value, and check that it exists before using it:
#!/usr/bin/env bash
set -euo pipefail
body=$(jq -n --argjson job_id 123 '{job_id: $job_id}')
run_id=$(databricks api post /api/2.1/jobs/run-now --json "$body" \
| jq -er '.run_id')
echo "Started run ${run_id}"Here jq -n builds the request body without any input. Building JSON with --argjson and --arg is safer than assembling it from shell string pieces. A value containing a quote or newline would break a hand-built string, and jq escapes it correctly. The -e flag makes jq exit non-zero if .run_id is missing, so the script stops instead of continuing with an empty variable. (The databricks api command is covered in a later chapter.)
Producing a report
jq can also format output for people or spreadsheets. @csv quotes fields correctly, which @tsv does not need to do:
#!/usr/bin/env bash
set -euo pipefail
{
echo "job_id,name"
databricks jobs list --output json \
| jq -r '.[]? | [.job_id, (.settings.name // "")] | @csv'
} > jobs.csvUse @csv when names might contain commas. The header line is added by the shell, since jq only prints what you ask for.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `jq: error: Cannot iterate over null` | The command returned `null` or nothing instead of an array. | Use `.[]?`, or `(. // [])`. |
| `parse error: Invalid numeric literal` | Non-JSON text reached jq, such as an error message or table output. | Add `--output json`. Do not redirect stderr into the pipe. |
| Script keeps going after a failed command | `pipefail` is not set. | Add `set -euo pipefail`. |
| Value prints with quotes, such as `"nightly_etl"` | jq prints JSON strings by default. | Add `-r`. |
| `Cannot index string with string "name"` | Wrong path, or the CLI version uses a different response shape. | Inspect the raw output with `jq .` and adjust the path. |
| Empty variable, then a confusing later error | A field was missing and jq printed `null`, or nothing. | Use `jq -e`, or add a `// "default"` fallback. |
Debugging a filter
Build filters step by step. Save a response once, then experiment without calling the API again:
databricks jobs list --output json > jobs.json
jq '.[0]' jobs.json # look at one element
jq '.[0] | keys' jobs.json # list its field names
jq '[.[]? | .settings.name] | length' jobs.jsonkeys shows what fields exist, which is faster than guessing from documentation. The response shape can differ slightly between CLI versions and between commands, so look at real output before writing the filter.
Limits of this approach
- Output stays in memory in jq. For very large lists, filter early or narrow the query, for example with a
--job-idargument, instead of downloading everything. - Pagination is hidden. Many CLI list commands fetch all pages for you, but raw REST calls do not. That is covered in the pagination chapter.
- Do not print secrets. Commands such as
databricks auth tokenreturn credentials. If you pipe them through jq, avoidechointo logs.
Exercise
Write a script fragment that prints the ID and name of every job whose name contains "etl" (any capitalization), as tab-separated lines. It must not fail when a job has no name or when the workspace has no jobs. Which jq features make it safe?
Show answer
databricks jobs list --output json | jq -r '.[]? | select((.settings.name // "") | asciidowncase | contains("etl")) | [.jobid, .settings.name] | @tsv'
.[]? produces no output instead of an error when the response is null. (.settings.name // "") replaces a missing name with an empty string, so ascii_downcase and contains never receive null. Because no job without a name can match "etl", the final .settings.name is always a real string.
Exercise
A script runs databricks clusters list --output json 2>&1 | jq -r '.[].cluster_id' and sometimes fails with "parse error". Give two changes that make it reliable.
Show answer
First, remove 2>&1, so error messages on stderr stay out of the JSON stream and are shown separately. Second, add set -euo pipefail at the top, so a failed databricks command stops the script instead of passing partial output to jq. Using .[]? instead of .[] also avoids a failure when the result is null.