Search code examples
jsonjmespath

Is there any method by which a parent key can be accessed based on a condition on a key in the child object in jmespath?


I have been working with parsing a big json file. I am unable to use jq as its been tested in our systems where it takes comparitively good amount of time for completion of parsing. We have been using Jmespath as it has been tested fine with json that we use. Sample json given below :-

{
  "student": [
    {
      "rob": {
        "roll": 12
      }
    },
    {
      "tom": {
        "roll": 9
      }
    },
    {
      "mary": {
        "roll": 21
      }
    }
  ]
}

The problem is , I would have to fetch all names of the students along with roll greater than 10.

I have initially worked on jq and the below syntax is what I am looking for in JMESPath.

".student | .[] | select(.[].roll>=10) | { name : keys[], rollno : .[].roll}"

Required output is

{
  "name": "rob",
  "rollno": 12
}
{
  "name": "mary",
  "rollno": 21
}

I currently do not have option of dealing this with problem through within program as the software design requires me to write native jmespath query than handling it in program side.


Solution

  • With this code: student[*].{name: keys(@)[0], rollno: *.roll | [0]} | @[?rollno > `10`]

    you will get this:

    [
      {
        "name": "rob",
        "rollno": 12
      },
      {
        "name": "mary",
        "rollno": 21
      }
    ]