jsonjq

JQ: How to get just part of a JSON object?


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: input and expected output: What is the jq #some-jq-magic-here?

$ echo '{"color":"yellow", "count":4}, "cherries": {"color":"red"}}' \  
  | jq #some-jq-magic-here
{
  "apples": {
    "color": "green",
    "count": 3
  },
  "cherries": {
    "color": "red"
  }
}

EDIT: ANSWER: The jq #some-jq-magic-here is this: jq '{apples, cherries}'. From own answer. See below.


Solution

  • Try jq '{apples, cherries}'

    Turns out the dots were wrong:

    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?