Jim
Jim

Reputation: 189

select value from subfield that is inside an array

I have a JSON object that looks something like this:

{
    "a": [{
        "name": "x",
        "group": [{
            "name": "tom",
            "publish": true
        },{
            "name": "joe",
            "publish": true
        }]
    }, {
        "name": "y",
        "group": [{
            "name": "tom",
            "publish": false
        },{
            "name": "joe",
            "publish": true
        }]
    }]
}

I want to select all the entries where publish=true and create a simplified JSON array of objects like this:

[
  {
    "name": "x"
    "groupName": "tom"
  },
  {
    "name": "x"
    "groupName": "joe"
  },
  {
    "name": "y"
    "groupName": "joe"
  }  
]

I've tried many combinations but the fact that group is an array seems to prevent each from working. Both in this specific case as well as in general, how do you do a deep select without loosing the full hierarchy?

Upvotes: 2

Views: 1681

Answers (3)

oguz ismail
oguz ismail

Reputation: 50795

A shorter, effective alternative:

.a | map({name, groupname: (.group[] | select(.publish) .name)})

Online demo

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158160

You can use this:

jq '.[]|map(
      .name as $n
      | .group[]
      | select(.publish==true)
      | {name:$n,groupname:.name}
    )' file.json

Upvotes: 6

Charles Duffy
Charles Duffy

Reputation: 295687

Using <expression> as $varname lets you store a value in a variable before going deeper into the hierarchy.

jq -n '
[inputs[][]
 | .name as $group
 | .group[]
 | select(.publish == true)
 | {name, groupName: $group}
]' <input.json

Upvotes: 5

Related Questions