0

I have a loop where I'm creating a json structure using jq. I create individual json structures with the following.

jq -n \
  --arg name $myname \
  --arg subject $mysubject \
  --arg version "1" \
  '{name: $name, subject: $subject, version: $version}'

But I want to concatenate each structure in to an array, like:

[
    {
      "name": "name1",
      "subject": "subj1",
      "version": "1"
    },
    {
      "name": "name2",
      "subject": "subj2",
      "version": "1"
    }
]

I'm trying something like this with pipes, but the array doesn't get populated.

$myarray=$myarray jq -n \
  --arg name $myname \
  --arg subject $mysubject \
  --arg version "1" \
  '{name: $name, subject: $subject, version: $version}'
9
  • 1
    Quotes matter. --arg name "$myname", --arg subject "$mysubject". By contrast, you don't need quotes around the 1 in --arg version 1 (they don't hurt anything, but they don't help you at all either). Otherwise names or subjects with whitespace will misbehave. Commented Mar 10, 2021 at 18:24
  • Beyond that, your code isn't trying to change myarray. Just like when you store any other command's output into a variable, you need to use a command substitution; we have lots of non-jq-specific duplicates on that. Commented Mar 10, 2021 at 18:25
  • ...f/e, How do I set a variable to the output of a command in bash? -- var=$(yourcommand); the $(...) is critical. Commented Mar 10, 2021 at 18:26
  • Here is an example that I use in many of my scripts: smtpHost=$(jq -r '.smtp.host' settings.json) Commented Mar 10, 2021 at 18:27
  • Mind, I wouldn't advise calling jq once per item at all -- that's wildly inefficient. Why not let jq parse your whole data feed all at once? Generate a single list of tab-separated items, one item per line, and tell jq to parse your tab-separated lines into a JSON list; there you are. Commented Mar 10, 2021 at 18:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.