Home > front end >  Parse JSON Elements in Array with jq
Parse JSON Elements in Array with jq

Time:12-31

I'm trying to figure out how to print just the attributes->preferences section in the following JSON example using jq. What's throwing me is that this is an array that contains multiple entries that are identified by an id key value pair and I need the attributes->preferences section just from the array element with id 1 without knowing the exact order of the array entries ahead of time.

[
  {
    "id": 1,
    "attributes": {
      "preferences": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4",
        ...
      }
    },
    ...
  },
  {
    "id": 2,
    ...
  },
  {
    "id": 4,
    ...
  },
  ...
]

My desired output would be:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": "value4",
  ...
}

CodePudding user response:

One option would be considering to eliminate null elements after picking them through use of the following path

jq '.[].attributes.preferences | select(. != null )' 

Demo

CodePudding user response:

jq '.[] | select( .id == 1 ) | .attributes.preferences'

Demo on jqplay

  • Related