skip to Main Content

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?

3

Answers


  1. 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
    
    Login or Signup to reply.
  2. If you want to change the context, first evaluate the variable into it, then update the context:

    jq -n --arg key foo '{} as $o | $o | .[$key] = 42'
    

    Demo

    If you want to update the contents of a variable based on its old value, shadow it with a new one of the same name using the old one’s reference in its body:

    jq -n --arg key foo '{} as $o | ($o | .[$key] = 42) as $o | …'
    

    Demo

    Note: for the latter one, cannot be empty.

    Login or Signup to reply.
  3. Variables in jq are immutable, which is why your first two statments give errors.

    The third statement succeeds because what changed is the current value of the pipe, not $o, you can see it with :

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

    You can simulate mutable variables with :

    $ jq -n --arg key foo '.o = {} | .o[$key] = 42 | .o'
    {
      "foo": 42
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search