Bill
Bill

Reputation: 2973

replace a key with array in bash

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

Upvotes: 2

Views: 215

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

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

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

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

Upvotes: 3

Related Questions