oliv
oliv

Reputation: 13239

Get field from JSON object using jq and command line argument

Assume the following JSON file

{ 
   "foo": "hello",
   "bar": "world"
}

I want to get the foo field from the JSON object in a standalone object, and I do this:

<file jq '{foo}'
{
   "foo": "hello"
}

Now the field I actually want is coming from the shell and is given to jq as an argument like this:

<file jq --arg myarg "foo" '{$myarg}'
{
   "myarg": "foo"
}

Unfortunately this doesn't give the expected result {"foo":"hello"}. Any idea why the name of the variable gets into the object?

A workaround to this is to explicitly defined the object:

<file jq '{($myarg):.[$myarg]}'

Fine, but is there a way to use the shortcut syntax as explained in the man page, but with a variable ?

You can use this to select particular fields of an object: if the input is an object with “user”, “title”, “id”, and “content” fields and you just want “user” and “title”, you can write

{user: .user, title: .title}

Because that is so common, there’s a shortcut syntax for it: {user, title}.

If that matters, I'm using jq version 1.5

Upvotes: 1

Views: 442

Answers (1)

peak
peak

Reputation: 116640

In short, no. The shortcut syntax can only be used under very special conditions. For example, it cannot be used with key names that are jq keywords.

Alternatives

The method described in the Q is the preferred one, but for the record, here are two alternatives:

jq --arg myarg "foo" '
  .[$myarg] as $v | {} | .[$myarg] = $v'

And of course there's the alternative that comes with numerous caveats:

myarg=foo ; jq "{ $myarg }"

Upvotes: 1

Related Questions