0

I need to use proper bash array to create a JQ array. I can't use , to split since I need to make use of the proper bash array in a forloop

I need to create a json array using bash array and pass it to --jsonarg.

This is the work around I used to pass to query 1.

group_list=("dummy group 1", "dummy group 2");
jsonarrray=$(echo ${group_list[@]} | jq -R 'split (" ")');

output:
[ "dummy group 1", "dummy group 2" ]

But I need to find a way to use the proper bash array without the comma.

group_list=("dummy group 1" "dummy group 2");
# Cannot use SPLIT because it won't produce separate values
jsonarrray=$(echo ${group_list[@]} | jq -R 'split (" ")');

output: 
[  "dummy group 1 dummy group 2" ]

Here is the query that I want to create. Query 1:

query_data=(jq -n --argjson groupsName "$jsonarrray" \
'{
    jsonrpc: "2.0",
    method: "hostgroup.get",
    params: {
        output: ["name", "groupid"],
        filter: {"name": $groupsName}
    },
    "auth": "6f38cddc44cfbb6c1bd186f9a220b5a0",
    "id": 2
}');

The final output of the query should look like this

{
  "jsonrpc": "2.0",
  "method": "hostgroup.get",
  "params": {
    "output": [
      "name",
      "groupid"
    ],
    "filter": {
      "name": [
        "dummy group 1",
        "dummy group 2"
      ]
    }
  },
  "auth": "6f38cddc44cfbb6c1bd186f9a220b5a0",
  "id": 2
}
user630702
  • 2,529
  • 5
  • 35
  • 98

1 Answers1

1

Easiest way to convert a bash array to a JSON array using JQ is to use --args option.

$ jq -n '$ARGS.positional' --args "${group_list[@]}"
[
  "dummy group 1",
  "dummy group 2"
]
oguz ismail
  • 1
  • 16
  • 47
  • 69