# For json.sh campi, with json.awk: the plain fields of the objects found at one place of a JSON text. # # LC_ALL=C awk -v percorso= -v campi= -f json.awk -f json-campi.awk ... # # percorso is the way from the root to the objects: keys and indexes separated by «/», «*» for any key or index, empty # for the root object itself. «*» is every object of a root list; «Results/*/Vulnerabilities/*» every vulnerability of # every result of Trivy. For each object found there, in the order of the text, one line with the values of campi in # the order asked, separated by a TAB: a string decoded (TAB, CR and LF inside become spaces, so a line stays a line), a # number as written, true, false and null as words; a field that is missing, or holds a list or an object, is empty. # # A file that is not a valid JSON text prints nothing at all (not even the lines found before the error): the reason # goes to stderr and the exit status is 2. A valid text with no object at that place prints nothing and exits with 0. BEGIN { steps = percorso == "" ? 0 : split(percorso, step, "/") wanted = split(campi, field, ",") for (i = 1; i <= wanted; i++) column[field[i]] = i broken = 0 } function json_begin(file) { inside = 0 rows = "" } function json_open(kind, d) { if (inside || kind != "o" || json_depth != steps + 1) return for (d = 1; d <= steps; d++) { if (step[d] != "*" && (json_at[d] "") != step[d]) return } inside = 1 split("", value) } function json_scalar(kind, text) { if (!inside || json_depth != steps + 1 || !((json_at[json_depth] "") in column)) return if (kind == "s") gsub(/[\t\r\n]/, " ", text) value[column[json_at[json_depth] ""]] = text } function json_close(kind, line, i) { if (!inside || json_depth != steps + 1) return inside = 0 line = "" for (i = 1; i <= wanted; i++) line = line (i > 1 ? "\t" : "") ((i in value) ? value[i] : "") rows = rows line "\n" } function json_end(file, error) { if (error != "") { print file ": " error > "/dev/stderr" broken = 1 } else { printf "%s", rows } } END { exit (broken ? 2 : 0) }