Search code examples
jsonkeyjq

How to get the name of the enclosing object while filtering for property values in that enclosed object


I have a JSON file that looks like this:

{
  "somename": {
    "prop1": "https://xxxx",
    "prop2": "xxxx",
    "prop3": false
  },
  "anothername": {
    "prop1": "https://yyyy",
    "prop2": "yyyy",
    "prop3": false
  },
  "fubar": {
    "prop1": "https://yyyy",
    "prop2": "yyyy",
    "prop3": false
  }
}

I mostly work with JSON files where the property NAMES of things are constant, and the VALUES vary, and I filter based on the values of named properties.

In this case, the "prop1", "prop2", and "prop3" properties are known, but the name of the enclosing object, essentially the name of that property, is what varies. It's those property names that I need to get. For instance, I need to get the list of named blocks where the "prop2" property is equal to "yyyy". In this case, it would be "anothername" and "fubar", but I can't figure out how to do that in jq.


Solution

  • Either will work

    to_entries[] | select(.value.prop2 == "yyyy") .key
    
    path(.[] | select(.prop2 == "yyyy"))[0]