1

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
}

1 Answer 1

2

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

$ jq -n '$ARGS.positional' --args "${group_list[@]}"
[
  "dummy group 1",
  "dummy group 2"
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.