bravesheeptribe
bravesheeptribe

Reputation: 189

How do I print the key along with the value in JQ?

For example, if I have the data below

{
    "test1": {
        "name": "John"
    },
    "test2": {
        "name": "Jack"
    },
    "test3": {
        "name": "Jim"
    },
    "test4": {
        "name": "John"
    }
}

and I wanted to get all the items where the name property is John, in the following format

{
    "test1": {
        "name": "John"
    },
    "test4": {
        "name": "John"
    }
}

How would I go about doing this? If I use the following JQ command: .[] | select(.name | ascii_downcase | contains("john")) it only returns

{
  "name": "John"
}
{
  "name": "John"
}

omitting the keys.

Upvotes: 1

Views: 373

Answers (2)

Philippe
Philippe

Reputation: 26422

To keep original structure, use map_values :

map_values(select(.name | ascii_downcase | contains("john")))

Upvotes: 3

pmf
pmf

Reputation: 36033

Use the update operator |= to (un)select each item while keeping the outer context:

jq '.[] |= select(.name | ascii_downcase | contains("john"))'
{
  "test1": {
    "name": "John"
  },
  "test4": {
    "name": "John"
  }
}

Demo

Upvotes: 1

Related Questions