Sub topic 11
JSON output and CycloneDX SBOMs
This chapter assumes you can run trivy image and read its table output, as covered in the previous chapters. It also assumes you know what an SBOM is in general terms. You should have jq and Python 3 installed for the examples. By the end you will be able to export Trivy results as JSON, extract fields from them, generate a CycloneDX SBOM, and scan that SBOM later without pulling the image again.
Why machine-readable output matters
The default table is for people. It truncates long titles, groups rows by target, and changes layout between versions. Scripts, dashboards, ticket systems and CI jobs need a stable structure instead. Trivy offers two exports that serve different purposes:
- JSON results list the vulnerabilities found in one scan. They answer the question "what is wrong with this image right now?"
- A CycloneDX SBOM lists the components in the image. It answers the question "what is in this image?" It is an inventory and does not depend on what is currently known to be vulnerable.
Keeping the two separate is useful. The inventory stays valid for as long as the image does. The findings go stale as new CVEs are published.
Writing JSON results
Use --format json with --output to write a file:
trivy image --format json --output result.json python:3.12-slimWithout --output, the JSON goes to standard output. Trivy's progress messages go to standard error, so redirecting stdout to a file also works. --output is clearer and avoids mixing streams.
The filters from the previous chapter still apply. Severity and unfixed filtering happen before the report is written, so a file produced with --severity HIGH,CRITICAL --ignore-unfixed contains only those findings.
The shape of the file
The top level describes the scanned artifact. The part you will use most is the Results array. Each entry is one scan target, such as the operating system package set or a language manifest inside the image.
{
"SchemaVersion": 2,
"ArtifactName": "python:3.12-slim",
"ArtifactType": "container_image",
"Results": [
{
"Target": "python:3.12-slim (debian 12.5)",
"Class": "os-pkgs",
"Type": "debian",
"Vulnerabilities": [
{
"VulnerabilityID": "CVE-2024-00000",
"PkgName": "libexample",
"InstalledVersion": "1.2.3-1",
"FixedVersion": "1.2.3-2",
"Severity": "HIGH",
"Title": "Example finding"
}
]
}
]
}The values above are illustrative, and real files carry many more fields per finding, such as PrimaryURL, References and CVSS. The fields to know are:
| Field | Meaning |
|---|---|
| `Target` | The place the packages were found, for example the OS or a `requirements.txt` path |
| `Class` | Broad category, such as `os-pkgs` or `lang-pkgs` |
| `VulnerabilityID` | The CVE or other advisory identifier |
| `PkgName`, `InstalledVersion` | The affected package and the version in the image |
| `FixedVersion` | The first version with a fix. It is absent when no fix exists |
| `Severity` | `UNKNOWN`, `LOW`, `MEDIUM`, `HIGH` or `CRITICAL` |
Querying with jq
This command prints one tab-separated line per finding, with a placeholder where no fix exists:
jq -r '
.Results[]
| .Target as $target
| (.Vulnerabilities // [])[]
| [$target, .VulnerabilityID, .PkgName, .InstalledVersion,
(.FixedVersion // "none"), .Severity]
| @tsv
' result.jsonThis one counts findings per severity:
jq '[.Results[].Vulnerabilities[]?]
| group_by(.Severity)
| map({severity: .[0].Severity, count: length})' result.jsongroup_by sorts and groups, so the output lists severities in alphabetical order, not by seriousness. Sort them yourself if the order matters.
Processing the file in Python
When the logic outgrows a jq one-liner, a short script is easier to maintain. This one lists fixable critical findings and exits non-zero if it finds any:
import json
import sys
with open("result.json", encoding="utf-8") as f:
report = json.load(f)
blocking = []
for result in report.get("Results", []):
for vuln in result.get("Vulnerabilities") or []:
if vuln.get("Severity") == "CRITICAL" and vuln.get("FixedVersion"):
blocking.append(vuln)
for vuln in blocking:
print(
f'{vuln["VulnerabilityID"]}: {vuln["PkgName"]} '
f'{vuln["InstalledVersion"]} -> {vuln["FixedVersion"]}'
)
sys.exit(1 if blocking else 0)or [] handles the missing key described in the warning above. For a simple threshold, --exit-code 1 in Trivy itself is easier. A script is the better choice when the rule depends on package names, targets or a custom allow list.
Generating a CycloneDX SBOM
CycloneDX is an SBOM standard maintained by OWASP. Trivy writes it as JSON:
trivy image --format cyclonedx --output sbom.cdx.json python:3.12-slimThe file declares its format with bomFormat and specVersion, then lists everything in a components array. Each component has a type, a name, a version and usually a purl.
A purl (package URL) is a standard string that identifies a package across ecosystems. Examples are pkg:deb/debian/[email protected] and pkg:pypi/[email protected]. Vulnerability databases match on these identifiers, so the purl is the most useful field in the file. Check what you got with jq:
jq '.components | length' sbom.cdx.json
jq -r '.components[] | select(.type == "library") | .purl' sbom.cdx.json | sort | head
jq -r '.components[] | select(.type == "operating-system") | "\(.name) \(.version)"' sbom.cdx.jsonTrivy records the base operating system as a component of type operating-system. Packages are of type library. Depending on the Trivy version, the file may also contain a dependencies array that records which component depends on which, and a vulnerabilities array. Treat those as version-dependent and check your own output before building a parser around them.
Scanning an SBOM later
An SBOM is useful because you can scan it without the image:
trivy sbom --severity HIGH,CRITICAL --ignore-unfixed sbom.cdx.jsonThis matches the stored component list against the current vulnerability database. A release made six months ago can be re-evaluated against today's advisories by scanning its archived SBOM. You do not need to pull the image or keep it in a registry. Storing the SBOM next to each release artifact (as a CI build artifact, or attached to the image in a registry) is the usual practice.
The SBOM can only describe what the generator could see. Software copied into the image as a single binary, with no package manager record, may be missing or reduced to a Go module list. A scan of the SBOM is therefore never more complete than the SBOM.
Docker Scout's equivalent
Docker Scout builds its own SBOM and can print it. docker scout sbom python:3.12-slim lists the packages it found, and docker scout sbom --help shows the available output formats. Run docker scout cves --help to see which report formats your version supports. Comparing a Scout package list with a Trivy SBOM is a quick way to see why the two tools sometimes report different findings.
Common errors
- Reading the wrong file. Running the scan with
> result.jsonwhile Trivy also prints logs to the terminal is fine. Running it with2>&1 > result.jsonin the wrong order, or capturing both streams together, corrupts the JSON. - Assuming zero findings means a clean image. An empty
Resultsarray can also mean Trivy found no supported package sources. Check.Metadata.OSor the SBOM component count. - Comparing SBOMs byte for byte. Files include serial numbers and timestamps, so two scans of the same image differ. Compare sorted purls instead.
- Treating the SBOM as a findings report. It lists what is installed. It does not say what is vulnerable unless the vulnerabilities array is present, and even then only as of generation time.
Exercise
You archived sbom.cdx.json when you released myapp 1.4. Three months later a new critical CVE affects one of its libraries. How do you check whether 1.4 is affected without pulling the image, and which Trivy flags keep the output limited to findings you can act on?
Show answer
Run trivy sbom --severity HIGH,CRITICAL --ignore-unfixed sbom.cdx.json. Trivy matches the stored component list against its current vulnerability database, so the new CVE appears if a listed purl is affected. --severity limits the report to high and critical findings. --ignore-unfixed hides findings with no fixed version yet.
Exercise
Write a jq command that prints the unique package names of all CRITICAL findings in result.json, and explain why (.Vulnerabilities // [])[] or .Vulnerabilities[]? is used instead of .Vulnerabilities[].
Show answer
jq -r '[.Results[] | (.Vulnerabilities // [])[] | select(.Severity == "CRITICAL") | .PkgName] | unique[]' result.json. Result entries with no findings have no Vulnerabilities key, so .Vulnerabilities[] fails on them. The // [] fallback (or the ? operator) treats a missing key as an empty list.