fix(api): rewrite json_escape to use awk for reliable JSON escaping

This commit is contained in:
CanbiZ (MickLesk)
2026-03-02 16:25:22 +01:00
parent cd38bc3a65
commit 8b62b8f3c5

View File

@@ -346,18 +346,20 @@ explain_exit_code() {
# - Handles backslashes, quotes, newlines, tabs, and carriage returns # - Handles backslashes, quotes, newlines, tabs, and carriage returns
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
json_escape() { json_escape() {
local s="$1" # Escape a string for safe JSON embedding using awk (handles any input size).
# Strip ANSI escape sequences (color codes etc.) # Pipeline: strip ANSI → remove control chars → escape \ " TAB → join lines with \n
s=$(printf '%s' "$s" | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g') printf '%s' "$1" \
s=${s//\\/\\\\} | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' \
s=${s//"/\\"/} | tr -d '\000-\010\013\014\016-\037\177\r' \
s=${s//$'\n'/\\n} | awk '
s=${s//$'\r'/} BEGIN { ORS = "" }
s=${s//$'\t'/\\t} {
# Remove any remaining control characters (0x00-0x1F except those already handled) gsub(/\\/, "\\\\") # backslash → \\
# Also remove DEL (0x7F) and invalid high bytes that break JSON parsers gsub(/"/, "\\\"") # double quote → \"
s=$(printf '%s' "$s" | tr -d '\000-\010\013\014\016-\037\177') gsub(/\t/, "\\t") # tab → \t
printf '%s' "$s" if (NR > 1) printf "\\n"
printf "%s", $0
}'
} }
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------