HRVSTR Posted April 26, 2020 Posted April 26, 2020 Hi, I am creating a workflow and I want to create a script filter with strings from a bash array. Given I have an array called $regions that contains 3 strings. I want to create 3 list items from that using jq. echo $regions france netherlands denmark I tried this command but the output is obviously not compliant with Alfreds JSON format. jq -n --arg inarr "${regions}" '{ items: [ $inarr | split("\n") ] }' { "items": [ [ "france", "netherlands", "denmark" ] ] } I need the JSON to look like that: {"items": [ { "uid": "france", "title": "france", "arg": "france", "autocomplete": "france", "icon": { "path": "icons/france.png" } }, { "uid": "netherlands", "title": "netherlands", "arg": "netherlands", "autocomplete": "netherlands", "icon": { "path": "icons/netherlands.png" } }, { "uid": "denmark", "title": "denmark", "arg": "denmark", "autocomplete": "denmark", "icon": { "path": "icons/denmark.png" } }, ]} Any help would be much appreciated.
Archite Posted June 20, 2020 Posted June 20, 2020 jq -n --argjson country '["france", "netherlands", "denmark"]' -f <(echo '{"items":[$country[] as $name | {"uid":$name,"title":$name,"arg":$name,"autocomplete":$name,"icon":{"path":("icons/" + $name + ".png")}}]}') gohoyer 1
gohoyer Posted January 30, 2022 Posted January 30, 2022 Just a minor improvement on @Archite awesome example converting a bash array to a json array, that way it becomes more reusable: #!/usr/bin/env bash # Declare your initial values regions="france netherlands denmark" # Converts your string to a bash array SAVEIFS=$IFS # Save current IFS (Internal Field Separator) IFS=' ' # Change IFS to space array=($regions) # split the `regions` string into an array IFS=$SAVEIFS # Restore original IFS # Converts the bash array to a json array json_array=$(printf '%s\n' "${array[@]}" | jq -R . | jq -s .) $ Format the output as Script Filter Json Format jq -n --argjson item "$json_array" -f <(echo '{"items":[$item[] as $name | {"uid":$name,"title":$name,"arg":$name,"autocomplete":$name,"icon":{"path":("icons/" + $name + ".png")}}]}')
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now