Home > Back-end >  How do I print the key along with the value in JQ?
How do I print the key along with the value in JQ?

Time:06-13

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.

CodePudding user response:

To keep original structure, use map_values :

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

CodePudding user response:

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

  • Related