Adam Carter
Adam Carter

Reputation: 35

Output key with the value

Given a json object (stored as bash variable $test)

{
  "foo": {
    "name": "my foo"
  },
  "bar": {
    "name": "my bar"
  }
}

If I want to output

{
  "foo": {
    "name": "my foo"
  }
}

It looks like I have to use

$ jq '. | with_entries(select(.key == "foo"))' <<<$test
{
  "foo": {
    "name": "my foo"
  }
}

Is there a simpler method to achieve same outcome?

Upvotes: 0

Views: 74

Answers (1)

peak
peak

Reputation: 116650

Yes!

jq '{foo}'

Explanation

{foo} is an abbreviation for {"foo": .foo}

:-)

Caveat

The abbreviated form can only be used for key names that are not jq keywords (such as if). However:

$ jq -n '{"if"}'
{
  "if": null
}

Upvotes: 2

Related Questions