Issue
I have variables with JSON:
export RESPONSE=$(curl -s --request POST --data "$some_data" $some_url)
In RESPONSE
{
"data": {
"warnings": "1",
"auth": "no"
... and a lot of variables
}
}
And I need to create variables how it:
$warnings="1"
$auth="no"
....
I only need variables from the field "data"
.
And in bash, as far as I understand, there is no to_entries
.
And yet, I need that the data from #RESPONSE is not written to the console while the script is running.
Update:
I have this working code but it writes all JSON to console and that's not what I want.
export ENV_SETTER=$(for i in $KEYS; do echo -n env.$i=$(echo $RESPONSE | jq -r .data.$i),;done)
Next i need this
--set "${ENV_SETTER}"
Solution
It is dangerous to set variables the way you want to. Already existing variables with the same name will be overwritten and this can damage your environment. Think about this security vulnerability beforehand.
I come up with two solutions
- using
eval
- avoiding
eval
Solution 1
eval $(jq -r '.data | to_entries | map("export " + .key + "='"'"'" + .value + "'"'"'")[]' "$FILE")
eval
executes the code generated by jq
:
export warnings='1'
export auth='no'
Remark
- the cryptic
'"'"'"
is notjq
syntax. It is a way to add single quotes to a string in bash
Solution 2
RESPONSE='
{
"data": {
"warnings": "1",
"auth": "no"
}
}
'
KEYS=$(jq -r '.data | keys[]' <<< "$RESPONSE")
for KEY in $KEYS; do
VALUE=$(jq -r --arg key "$KEY" '.data | .[$key]' <<< "$RESPONSE")
read "$KEY" <<< "$VALUE"
done
Answered By - jpseng Answer Checked By - Senaida (WPSolving Volunteer)