1

How can I get my wanted output? I can't figure out how to preserve the object names (keys).

I'm new to jq and I tried several flavors of jq's select/flatten/map/","/"keys as $k".../etc. but I'm not getting anywhere.

Input

$ echo '{"apples": {"color":"green",  "count":3}, "bananas": {"color":"yellow", "count":4}, "cherries": {"color":"red"}}' \  
  | jq .
{
  "apples": {
    "color": "green",
    "count": 3
  },
  "bananas": {
    "color": "yellow",
    "count": 4
  },
  "cherries": {
    "color": "red"
  }
}

Actual Output

This is the best I got but the object names are gone:

$ echo '{"apples": {"color":"green",  "count":3}, "bananas": {"color":"yellow", "count":4}, "cherries": {"color":"red"}}' \  
  | jq '.apples, .cherries'
{
  "color": "green",
  "count": 3
}
{
  "color": "red"
}

Expected Output

This is what I want:

{"color":"yellow", "count":4}, "cherries": {"color":"red"}}' \  
  | jq #some-jq-magic-here
{
  "apples": {
    "color": "green",
    "count": 3
  },
  "cherries": {
    "color": "red"
  }
}
StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
  • 1
    In your case: `{apples, cherries}` – Benjamin W. Nov 03 '21 at 11:03
  • 2
    I'm not sure the selected https://stackoverflow.com/questions/34834519/how-do-i-select-multiple-fields-in-jq is an ideal duplicate target. That question is more vague than this one and while the desired answer _is_ there it's neither the accepted nor the most upvoted answer at present. – Weeble Nov 03 '21 at 14:04

2 Answers2

3

jq '{apples, cherries}' instead of jq '{.apples, .cherries}'

I tried with dots first: jq '{.apples, .cherries}'. That did NOT work.

But WITHOUT the dots it works just fine:

$ echo '{
  "apples":   { "color":"green",  "count": 3 },
  "bananas":  { "color":"yellow", "count": 4 },
  "cherries": { "color":"red" }
}' | jq '{apples, cherries}'
{
  "apples": {
    "color": "green",
    "count": 3
  },
  "cherries": {
    "color": "red"
  }
}

Related: How do I select multiple fields in jq?

StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
  • RE "*I tried with dots first*", `{apples, cherries}` is short for `{apples: .apples, cherries: .cherries}` – ikegami Nov 03 '21 at 16:26
0
echo '...' | jq 'with_entries(select([.key] | inside(["apples", "cherries"])))'

Thanks https://stackoverflow.com/a/46293052/9216229

Marco Caberletti
  • 1,353
  • 1
  • 10
  • 13
  • Thanks. That works! But I'll never remember that syntax. So I went for a more concise version: https://stackoverflow.com/a/69825482/4247268 – StackzOfZtuff Nov 03 '21 at 13:14
  • You could also use `IN()`: `with_entries(select(.key | IN("apples","cherries")))`. But it is easiest to just `{apples, cherries}`. – Logan Lee May 03 '22 at 00:58