Skip to content

Commit d3e2077

Browse files
authored
Allow multiple lines in var.json (#104)
1 parent 854f8d6 commit d3e2077

1 file changed

Lines changed: 27 additions & 4 deletions

File tree

lib/var.sh

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,14 +139,17 @@ function bashio::var.json() {
139139

140140
counter=0;
141141
for i in "${data[@]}"; do
142+
item="\"$i\""
143+
142144
separator=","
143145
if [ $((++counter%2)) -eq 0 ]; then
144146
separator=":";
145-
fi
146147

147-
item="\"$i\""
148-
if [[ "${i:0:1}" == "^" ]]; then
149-
item="${i:1}"
148+
if [[ "${i:0:1}" == "^" ]]; then
149+
item="${i:1}"
150+
else
151+
item=$(bashio::var.json_string "${i}")
152+
fi
150153
fi
151154

152155
json="$json$separator$item";
@@ -156,3 +159,23 @@ function bashio::var.json() {
156159
return "${__BASHIO_EXIT_OK}"
157160
}
158161

162+
# ------------------------------------------------------------------------------
163+
# Escapes a string for use in a JSON object.
164+
#
165+
# Arguments:
166+
# $1 String to escape
167+
# ------------------------------------------------------------------------------
168+
function bashio::var.json_string() {
169+
local string="${1}"
170+
local json_string
171+
172+
# https://stackoverflow.com/a/50380697/12156188
173+
if json_string=$(echo -n "${string}" | jq -Rs .); then
174+
echo "${json_string}"
175+
return "${__BASHIO_EXIT_OK}"
176+
fi
177+
178+
bashio::log.error "Failed to escape string"
179+
return "${__BASHIO_EXIT_NOK}"
180+
}
181+

0 commit comments

Comments
 (0)