1

I need to remove run_list values between [] and replace them with a variable I define in a.

RUNLIST:

{
  "name": "blah200.blah.stage.blahblah.com",
  "chef_environment": "blahenv",
  "run_list": [
  "recipe[blah1]",
  "recipe[blah2]",
  "recipe[blah3]",
  "recipe[blah4]",
  "recipe[blah5]",
  "recipe[blah6]",
  "recipe[blah7]",
  "recipe[blah8]",
  "recipe[blah9]"
]
,
  "normal": {
    "tags": [
      "run_once"
    ],
    "selinux": {
      "status": "disabled"
    },
    "blah_pkger": {
      "access": {
        "blah": "x.x.x.x"
      }
    }
  }
}
a="[ recipe[blah11], recipe[blah12], recipe[blah12], recipe[blah13], recipe[blah14], recipe[blah15], recipe[blah16], recipe[blah17], recipe[blah18], recipe[blah19], recipe[blah20], recipe[blah21], recipe[blah22], recipe[blah23] ]"

I know I can do something like

jq --args newval $a '(.run_list[]| select(.run_list))|= $newval' file.json > tmp.json

but it is failing giving me this error:

jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at <top-level>, line 1:

1 Answer 1

1

Assuming you have your new array elements in a shell array like so:

a=(
        'recipe[blah11]' 'recipe[blah12]' 'recipe[blah12]' 'recipe[blah13]'
        'recipe[blah14]' 'recipe[blah15]' 'recipe[blah16]' 'recipe[blah17]'
        'recipe[blah18]' 'recipe[blah19]' 'recipe[blah20]' 'recipe[blah21]'
        'recipe[blah22]' 'recipe[blah23]'
)

Then you may replace the run_list array with these elements like so:

jq '.run_list = $ARGS.positional' file --args "${a[@]}"

... where your document is stored in file.

The --args option must be the last option on the command line of jq, and the array is expanded into individually quoted strings after it. Inside the jq expression, those strings are available as the array $ARGS.positional, and we simply assign this array to the correct place in the document.

If you have the new values as a valid JSON array in a scalar shell variable,

a='[
  "recipe[blah11]", "recipe[blah12]", "recipe[blah12]", "recipe[blah13]",
  "recipe[blah14]", "recipe[blah15]", "recipe[blah16]", "recipe[blah17]",
  "recipe[blah18]", "recipe[blah19]", "recipe[blah20]", "recipe[blah21]",
  "recipe[blah22]", "recipe[blah23]"
]'

Then you could do

jq --argjson value "$a" '.run_list = $value' file

Note that you will have to use --argjson here as you want jq to use $a as a JSON document fragment, not to encode the value as a string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .