Sub topic 12
Use JSON output in scripts
Every sf command prints text meant for people. That text is good for reading in a terminal, but it is a poor input for a script. Column widths change, messages get reworded, and progress lines get mixed into the output. The --json flag solves this. It makes the command print one JSON document with a stable structure, which a script can parse.
This chapter assumes you can run sf commands, that you have a default target org (see "Aliases and the default target org"), and that you know basic JSON syntax. The examples use jq, a command-line JSON processor, and Python 3.
What --json changes
Add --json to a command and it prints a single JSON object instead of formatted text. Almost every sf command supports the flag. Take the query from the earlier chapter:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --jsonThe output looks like this (shortened to two records):
{
"status": 0,
"result": {
"records": [
{
"attributes": {
"type": "Account",
"url": "/services/data/v62.0/sobjects/Account/001000000000001AAA"
},
"Id": "001000000000001AAA",
"Name": "Acme"
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v62.0/sobjects/Account/001000000000002AAA"
},
"Id": "001000000000002AAA",
"Name": "Globex"
}
],
"totalSize": 2,
"done": true
},
"warnings": []
}The envelope is the same for every command:
| Field | Meaning |
|---|---|
| `status` | `0` on success. A non-zero value means the command failed. |
| `result` | The command's payload. Its shape depends on the command. |
| `warnings` | An array of warning messages. It is empty when there are none. |
Only result varies from command to command. For sf data query it holds records, totalSize, and done. For sf org display it holds the org's username, instance URL, and connection status. When you meet a new command, run it once with --json and read the shape before you write code against it.
The API version in the url values (v62.0 above) depends on your org and CLI version, so yours may differ.
Why the exit code matters
A script has two signals for success: the process exit code and the status field. They agree. A successful command exits with 0, and a failed one exits with a non-zero code. In JSON mode a failure still prints a JSON document to standard output, but the document has a different shape:
{
"status": 1,
"name": "INVALID_FIELD",
"message": "No such column 'Nme' on entity 'Account'.",
"exitCode": 1,
"commandName": "Query",
"warnings": []
}On failure there is no result. You get name, message, and exitCode at the top level instead. The exact fields can vary by command and error, so a script should check status first and read message only when the command failed.
Pull values out with jq
jq reads JSON from standard input and applies a filter. The leading dot is the root of the document, and .result.records walks into the payload.
Print only the account names, one per line:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --json \
| jq -r '.result.records[].Name'The -r flag prints raw strings without JSON quotes. The [] after records iterates over every element in the array.
Build tab-separated rows, which is handy for cut, sort, or a spreadsheet import:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --json \
| jq -r '.result.records[] | [.Id, .Name] | @tsv'Here the pipe inside the jq filter passes each record into the array constructor [.Id, .Name]. The @tsv formatter then turns that array into a tab-separated line.
Count the records:
sf data query --query "SELECT Id FROM Account" --json | jq '.result.totalSize'Use totalSize for the count rather than counting array elements yourself. It reports the total the query matched.
A complete shell script
The script below runs a query against a chosen org, stops cleanly on failure, and prints a report. It takes the org alias as its first argument and falls back to myorg.
#!/usr/bin/env bash
set -euo pipefail
ORG="${1:-myorg}"
QUERY="SELECT Id, Name FROM Account LIMIT 5"
if ! output=$(sf data query --query "$QUERY" --target-org "$ORG" --json); then
echo "Query failed: $(echo "$output" | jq -r '.message // "unknown error"')" >&2
exit 1
fi
total=$(echo "$output" | jq '.result.totalSize')
echo "Found $total account(s) in $ORG:"
echo "$output" | jq -r '.result.records[] | "- \(.Name) (\(.Id))"'Several details are worth noting:
set -euo pipefailstops the script when a command fails, when a variable is unset, or when any command in a pipeline fails.- The
if ! output=$(...)form captures the output and still lets you handle the failure. With plainoutput=$(...),set -ewould end the script before you could print the error message. - The
//operator in jq supplies a fallback when.messageis missing or null. --target-orgoverrides the default org for this one command. Passing it explicitly makes the script independent of whatever default the user's machine has.- Quoting
"$QUERY"and"$ORG"keeps spaces and special characters in the values from splitting into separate arguments.
The flow of the script is a loop you will repeat in most automation:
Parse the output in Python
When the logic outgrows a shell script, run sf from a program and parse the JSON with a standard library. This Python helper wraps the same pattern:
import json
import subprocess
import sys
def sf_json(*args):
"""Run an sf command with --json and return its result payload."""
proc = subprocess.run(
["sf", *args, "--json"],
capture_output=True,
text=True,
)
try:
payload = json.loads(proc.stdout)
except json.JSONDecodeError:
sys.exit(f"No JSON from sf: {proc.stderr.strip()}")
if proc.returncode != 0 or payload.get("status") != 0:
sys.exit(f"sf failed: {payload.get('message', 'unknown error')}")
return payload["result"]
result = sf_json(
"data", "query",
"--query", "SELECT Id, Name FROM Account LIMIT 5",
)
for record in result["records"]:
print(record["Id"], record["Name"])The helper passes the arguments as a list, so no shell is involved and quoting problems cannot occur. It handles two failure cases separately. If stdout is not JSON at all, for example because sf is not installed or crashed early, it reports stderr. If the JSON reports an error, it reports message.
On Windows, the sf launcher is a .cmd file. If subprocess.run cannot find sf, use "sf.cmd" as the first list element.
Inspect a different command
The same approach works for any command. To read the connection details of an org:
sf org display --target-org myorg --json | jq '.result | {username, instanceUrl, connectedStatus}'This filter builds a new object from three fields of result. It is a quick way to check in a script whether an org is still connected before you start a long deploy.
Common errors
- Parsing text mixed with JSON. If you redirect standard error into the same stream (
2>&1), warnings or progress text can end up in front of the JSON and break the parser. Keep stdout and stderr separate, and parse only stdout. - Reading
resultafter a failure.resultdoes not exist on an error document. In jq,.result.records[]on a failure prints nothing and can look like an empty result set. Check the exit code first. - Assuming the shape. The structure of
resultdiffers for each command, and it can gain fields in newer CLI versions. Select the fields you need by name and ignore the rest. - Relying on the default org. A script that runs on a build server may have no default org, or a different one. Pass
--target-orgexplicitly in automation. - Forgetting that queries can be large. A query that matches many records returns them all in one JSON document, which is slow to parse and heavy on memory. Use
LIMIT, or narrow theWHEREclause, when you only need a sample. - Using
jqwithout it being installed.jqis a separate tool and does not come with the Salesforce CLI. Install it with your package manager, or use Python as shown above.
Quick reference
| Task | Command or filter |
|---|---|
| Get JSON from a command | Add `--json` |
| Get one field as plain text | `jq -r '.result.records[].Name'` |
| Get the record count | `jq '.result.totalSize'` |
| Get an error message | `jq -r '.message'` |
| Check for success in jq | `jq -e '.status == 0'` |
| Target a specific org | `--target-org myorg` |
The -e flag makes jq exit with a non-zero code when the last output is false or null, so jq -e '.status == 0' can sit directly in an if statement.
Exercise
A script runs output=$(sf data query --query "SELECT Id FROM Account" --json) and then echo "$output" | jq '.result.totalSize'. The query has a typo in a field name, and the script prints null. Why does it print null, and what should the script check first?
Show answer
A failed command prints a JSON error document that has no result field, so .result.totalSize evaluates to null. The script should check the exit code of the sf command (or the status field) before it reads result. On failure it should read .message from the document and report it.
Exercise
Write a command that prints only the Name of each account, one per line, for the org with alias myorg, without relying on the default target org.
Show answer
sf data query --query "SELECT Name FROM Account LIMIT 5" --target-org myorg --json | jq -r '.result.records[].Name'