Tuesday, October 4, 2022

[SOLVED] How to Add a JSON Field to the Root JSON Object Using jq

Issue

I am trying to create the following JSON object structure:

{
  "hard-coded-value": false,
  "dynamic-value-1": true,
  "dynamic-value-2": true,
  "dynamic-value-3": true
}

My array of dynamic values is called DYNAMIC_VALUES.

I wrote the following bash code:

DYNAMIC_VALUES=("dynamic-value-1" "dynamic-value-2" "dynamic-value-3")

JSON_OBJECT=$( jq -n '{"hard-coded-value": false}' )

for i in "${DYNAMIC_VALUES[@]}"
do
    JSON_OBJECT+=$( jq -n \
                      --arg key "$i" \
                      '{($key): true}' )
done

echo $JSON_OBJECT

The above code prints the following

{ "hard-coded-value": false }{ "dynamic-value-1": true }{ "dynamic-value-2": true }{ "dynamic-value-3": true }

What I want is this output to look like the output outlined at the top of this question, but I can't figure out how to tell jq to append to the root JSON object instead of creating a bunch of objects.


Solution

You don't need a loop there.

$ dynamic_values=('dynamic-value-1' 'dynamic-value-2' 'dynamic-value-3')
$ printf '%s\n' "${dynamic_values[@]}" | jq -nR '{hardcoded_value: false} | .[inputs] = true'
{
  "hardcoded_value": false,
  "dynamic-value-1": true,
  "dynamic-value-2": true,
  "dynamic-value-3": true
}

This will break if one of the array elements contains a line feed though. For that JQ 1.6 has --args, which can be used as shown below.

$ dynamic_values=('dynamic-value-1' $'dynamic-value-2\n' 'dynamic-value-3')
$ jq -n '{hardcoded_value: false} | .[$ARGS.positional[]] = true' --args "${dynamic_values[@]}"
{
  "hardcoded_value": false,
  "dynamic-value-1": true,
  "dynamic-value-2\n": true,
  "dynamic-value-3": true
}


Answered By - oguz ismail
Answer Checked By - Mildred Charles (WPSolving Admin)