From be54486baf456b8b04a7f5f4989199e2a64f872c Mon Sep 17 00:00:00 2001 From: Felipe Santos Date: Mon, 7 Mar 2022 09:54:55 -0300 Subject: [PATCH] Allow multiple lines in var.json --- lib/var.sh | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/lib/var.sh b/lib/var.sh index 91b71ee..bb8316c 100644 --- a/lib/var.sh +++ b/lib/var.sh @@ -139,14 +139,17 @@ function bashio::var.json() { counter=0; for i in "${data[@]}"; do + item="\"$i\"" + separator="," if [ $((++counter%2)) -eq 0 ]; then separator=":"; - fi - item="\"$i\"" - if [[ "${i:0:1}" == "^" ]]; then - item="${i:1}" + if [[ "${i:0:1}" == "^" ]]; then + item="${i:1}" + else + item=$(bashio::var.json_string "${i}") + fi fi json="$json$separator$item"; @@ -156,3 +159,23 @@ function bashio::var.json() { return "${__BASHIO_EXIT_OK}" } +# ------------------------------------------------------------------------------ +# Escapes a string for use in a JSON object. +# +# Arguments: +# $1 String to escape +# ------------------------------------------------------------------------------ +function bashio::var.json_string() { + local string="${1}" + local json_string + + # https://stackoverflow.com/a/50380697/12156188 + if json_string=$(echo -n "${string}" | jq -Rs .); then + echo "${json_string}" + return "${__BASHIO_EXIT_OK}" + fi + + bashio::log.error "Failed to escape string" + return "${__BASHIO_EXIT_NOK}" +} +