jsonjqvariable-assignment

jq: assigning to computed property of an object


I'm trying to get jq to generate an object whose keys are computed.

This didn't work:

$ jq -n --arg key foo '{} as $o | $o[$key] = 42'
jq: error (at <unknown>): Invalid path expression near attempt to access element "foo" of {}

This didn't, either:

$ jq -n --arg key foo '{} as $o | ($o | .[$key]) = 42'
jq: error (at <unknown>): Invalid path expression near attempt to access element "foo" of {}

But this worked:

$ jq -n --arg key foo '{} as $o | ($o | setpath([$key]; 42))'
{
  "foo": 42
}

So, my question is, is there an assignment syntax that can produce the same effect?


Solution

  • The left hand side of the equals sign must be a value in .. Make $o . and then do the assignment like so:

    $o | .[$key] = 42