Jump to content

Construct script filter JSON with jq from bash array

Recommended Posts

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": [

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.

Link to comment
  • 1 month later...
  • 1 year later...

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")}}]}')


Link to comment

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...