I am following the ideas from the stackexchange articles below
- here to select and delete an element Delete Element
- here to append an element: Add New Element
but I am having problems with quotes when selecting and adding.
this is my sample json file
{
"options": [
{
"label": "22",
"value": "2022"
},
{
"label": "23",
"value": "2023"
}
]
}
and this is my test bash script
#!/bin/bash
previous_year=$(date --date="$(date +'%Y') - 1 year" +%Y)
last_year=$((previous_year + 31))
label=$((last_year -2000))
echo ${last_year}
jq 'del(.options[]? | select(.label == \"${previous_year}\"))' temp.json
jq '.options += [{
"label": '${label}',
"value": '${last_year}'
}]' temp.json
If I run the bash script with this sample file I get
jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at , line 1:
del(.options[]? | select(.label == "${previous_year}"))
jq: 1 compile error
If I remove the " it runs but don't find anything to delete because it looks without the quotes. It also add the element to the array but without quotes.
How can I do it?
- find the element with quotes
- add element with quotes
The expected result (what I want to achieve) is
{
"options": [
{
"label": "23",
"value": "2023"
},
{
"label": "53",
"value": "2053"
}
]
}
--argfor the variables ... btw, yourdelcommand should select onvaluenotlabelprevious_yearetc are all bash variables, not jq variables; you need to copy them into jq variables with--arg. See "Passing bash variable to jq" on stackoverflow.jqquery expression in double quotes and then have your variables interpolated, but this has serious robustness issues if one of the variables is empty or contains weird quoting etc. In the limit, you are opening up yourself to a "little Bobby Tables" attack. Just go with the standard solution.