0

I am trying to add a field to the data variable. Initially, it is

{ "objects": [] }

I want to add another field called objects_count such that

{ "objects": [], "objects_count": 1 }

Here is what I have so far:

echo $data
    
data=$( $data | jq --argjson oc "$objects_count" '. + {objects_count: $oc}' )

echo $data

And its output:

{ "objects": [] }

./scripts.sh: line 42: {: command not found

{ "objects_count": 1 }

Why is it not appending the field, and creating a new object instead?

  • 1
    `$data | ...` needs to be `echo "$data" | ...` or `<<<"$data" ...` or `... <<<"$data"` -- this is another general shell syntax problem that has nothing to do with jq in particular. – Charles Duffy Aug 29 '22 at 16:23
  • @0stone0, not really, because it would still be trying to run the JSON document as a command without `echo` specified. It's a necessary change for correct behavior, but not a sufficient one. – Charles Duffy Aug 29 '22 at 16:24
  • Thought that that question was used for quote related dupes. Might not be exact match, but quoting is causing the unexpected output – 0stone0 Aug 29 '22 at 16:25
  • @0stone0, it would be _different_ unexpected output without the quoting problem, but still unexpected output. With `"$data" | ...`, they'd get something like `./scripts.sh: line 42: { "objects": [], "objects_count": 1}: command not found` – Charles Duffy Aug 29 '22 at 16:25
  • BTW, `echo $data` should also be `echo "$data"` -- see [I just assigned a variable, but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Aug 29 '22 at 16:29
  • @CharlesDuffy Thanks, your suggestion worked! Also I realized that I needed to remove `-n` from the jq command. – inquisitivemongoose Aug 29 '22 at 16:30

0 Answers0