Tricky question here.
I have a function that modifies the content of a given JSON string by using osa script native JavaScript capabilities:
function set_json {
local json_source_data="$1"
local json_key="$2"
local json_key_value="$3"
if [[ "$#" -lt "3" ]]; then
echo "Arguments missing. You must provide at least three valid arguments: set_json json_source_data json_key json_key_value"
return 1
fi
read -r -d '' js_code_to_run <<EOF
const env = $.NSProcessInfo.processInfo.environment.objectForKey('json_content').js;
parsedJSON = JSON.parse(env);
parsedJSON.$json_key = '$json_key_value';
modified_json = JSON.stringify(parsedJSON, null, 2);
modified_json
EOF
json_data_modified=$(json_content="$json_source_data" /usr/bin/osascript -l "JavaScript" <<< "${js_code_to_run}")
if [[ -n $json_data_modified ]]; then
echo "$json_data_modified"
else
return 1
fi
}
It works perfectly fine for standard JSON name-value pairs with names like “whatever” or “what_ever”.
The problem is, some names have been given (improperly IMO) names such as: “name-key”.
This causes the function to crash:
115:145: syntax error: Error on line 3: SyntaxError: Left hand side of operator '=' must be a reference. (-2700)
As apparently the “-” causes JS to mess things up. I am finding a way to take the $json_key variable I am passing escaped (taking the “-” in “name-key” as a string, not something else) but I can’t find a way to do so given my poor JavaScript skills.
Help is welcome!


