Home > front end >  Filter element based on property's list bash/jq
Filter element based on property's list bash/jq

Time:06-08

Given the List:

[
    {
        "prop1": "prop11",
        "prop2": "prop21",
        "list": ["element1", "element2", "element3"]
    },
    {
        "prop1": "prop12",
        "prop2": "prop22",
        "list": ["element1", "element3"]
    },
    {
        "prop1": "prop13",
        "prop2": "prop23",
        "list": ["element2", "element3"]
    }
]

While using jq, how to filter only the root's list elements by the children's lists. For example, return all elements whose list contains element1. The output should be:

[
    {
        "prop1": "prop11",
        "prop2": "prop21",
        "list": ["element1", "element2", "element3"]
    },
    {
        "prop1": "prop12",
        "prop2": "prop22",
        "list": ["element1", "element3"]
    }
]

or

{"prop1": "prop11","prop2": "prop21","list": ["element1", "element2", "element3"]}
{"prop1": "prop12","prop2": "prop22","list": ["element1", "element3"]}

CodePudding user response:

Check if any of the list's element equals == the given string:

jq 'map(select(any(.list[]; . == "element1")))'
[
  {
    "prop1": "prop11",
    "prop2": "prop21",
    "list": [
      "element1",
      "element2",
      "element3"
    ]
  },
  {
    "prop1": "prop12",
    "prop2": "prop22",
    "list": [
      "element1",
      "element3"
    ]
  }
]

Demo


Use .[] | … instead of map(…) to get rid of the outer array:

jq '.[] | select(any(.list[]; . == "element1"))'
{
  "prop1": "prop11",
  "prop2": "prop21",
  "list": [
    "element1",
    "element2",
    "element3"
  ]
}
{
  "prop1": "prop12",
  "prop2": "prop22",
  "list": [
    "element1",
    "element3"
  ]
}

Demo

CodePudding user response:

index makes for a short and in practice quite fast solution:

jq 'map(select(.list|index("element1")))'

or

jq -c '.[] | select(.list|index("element1"))'
  • Related