2

Sample json file payload.json.tpl:

{
  "foo": "bar",
  "x": {
    "y": "${array}"
  }
}

I have an array in bash

array=("one" "two" "three")

How can I run the jq command to replace the key .x.y to ["one", "two", "three"]

So the final json will be:

{
  "foo": "bar",
  "x": {
    "y": ["one", "two", "three"]
  }
}

2 Answers 2

3

Using $ARGS.positional (requires jq 1.6)

$ array=("one" "two" "three")
$ jq '.x.y = $ARGS.positional' payload.json.tpl --args "${array[@]}"
{
  "foo": "bar",
  "x": {
    "y": [
      "one",
      "two",
      "three"
    ]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Like this, works with jq < 1.6 too:

< payload.json.tpl jq --arg a "${array[*]}" '.x.y=($a|split(" "))'

Note the use of ${array[*]} instead of ${array[@]}. When using *, the elements of ${array} will be passed as a single string instead of multiple strings.

https://www.gnu.org/software/bash/manual/html_node/Arrays.html

3 Comments

It has to be noted that this won't work for arrays whose elements themselves contain spaces, which is the primary reason to use a shell array over a space-separated string in the first place. (Though you may be able to construct a string using a delimiter that doesn't appear in any element.)
No delimiter was used to declare the array; that's the point. It's the conversion of the array to a single string that gets bound to a that can pose a problem. (I still think this answer is useful if one is stuck with an older version of jq, but the drawbacks still have to be acknowledged.)
yeah, I realized that after posting my comment. Thanks for the feedback here!!

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.