Home > Blockchain >  How do I use jq to append an array to this json string?
How do I use jq to append an array to this json string?

Time:10-29

I want to append this array to this json string using jq. My result only adds the hello element

method=1234
arraynew=(hello world)
echo $arraynew
PAYLOAD=$( jq -Rn \
                  --arg method $method \
                  --arg array $arraynew \
                  '{method: [$method], values: $array}' )

I get this return:

{ "method": [ "1234" ], "values": "hello" }

CodePudding user response:

try it

jq '.[].method  = [$method]'

CodePudding user response:

Referring to an array like $arraynew is equivalent to ${arraynew[0]} -- you only get the first element.

jq expects the --arg values to be strings, so we need to join the array into a single string, and then split it within jq:

jq -n \
   --arg method "$method" \
   --arg array  "$(printf '%s\n' "${arraynew[@]}")" \
    '
        {
            method: [$method],
            values: ($array | split("\n"))
        }    
    '
{
  "method": [
    "1234"
  ],
  "values": [
    "hello",
    "world"
  ]
}

CodePudding user response:

First, convert your bash array into a json array using jq

printf '%s\0' "${arraynew[@]}" | jq -Rns 'input | split("\u0000")'
[
  "hello",
  "world"
]

Then, import it to your main jq script using --argjson instead of --arg

jsonarray="$(
  printf '%s\0' "${arraynew[@]}" | jq -Rns 'input | split("\u0000")'
)"

jq -Rn \
  --arg method "$method" \
  --argjson array "$jsonarray" \
  '{method: [$method], values: $array}'
{
  "method": [
    "1234"
  ],
  "values": [
    "hello",
    "world"
  ]
}

CodePudding user response:

You can either pass your array elements as positional arguments:

#!/usr/bin/env bash

method=1234
arraynew=(hello world)
declare -p arraynew
payload=$(
  jq -n '{method: $method, values: $ARGS.positional}' \
    --arg method "$method" \
    --args "${arraynew[@]}"
)
printf '%s\n' "$payload"

But it has the limitation of system's maximum argument line length, so will work only with shorter arrays of small elements.

Or you can pass your array as a null-delimited elements stream, and have jq read it into a string to be split on null delimiters into a JSON array like this:

#!/usr/bin/env bash

method=1234
arraynew=(hello world)
declare -p arraynew

payload=$(
  printf '%s\0' "${arraynew[@]}" |
  jq -Rs '{method: $method, values: split("\u0000")}' \
    --arg method "$method"
)
printf '%s\n' "$payload"
  • Related