skip to Main Content

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.

2

Answers


  1. Either will work

    to_entries[] | select(.value.prop2 == "yyyy") .key
    
    path(.[] | select(.prop2 == "yyyy"))[0]
    
    Login or Signup to reply.
  2. One way would be to first filter the outer object using select inside map_values (or .[] |=), and then get all its keys:

    map_values(select(.prop2 == "yyyy")) | keys
    
    [
      "anothername",
      "fubar"
    ]
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search