skip to Main Content

How can I get the top 5 keys with the highest values from a JSON using JSONata?

Let’s say I have something like this. They keys aren’t alphabetically ordered, but the values are descending and I want to only show the first 5 keys&values:

[
 [
  {
   "key": A,
   "value": 310
  },
   "key": B,
   "value": 240
  },
   "key": C,
   "value": 110
  },
   "key": D,
   "value": 90
  },
   "key": E,
   "value": 60
  },
   "key": F,
   "value": 50
  },
   "key": G,
   "value": 30
  },
   "key": H,
   "value": 10
  }
 ]
]

What I would like to get is this:

[
  {
   "key": A,
   "value": 310
  },
   "key": B,
   "value": 240
  },
   "key": C,
   "value": 110
  },
   "key": D,
   "value": 90
  },
   "key": E,
   "value": 60
  }
]

Thank you!!!

2

Answers


  1. You can use the Positional Variable Binding path operator to determine at which position in the sequence the current context item is located and then filter by that position. This will get you the first N items in an array.

    For example, given your [cleaned up] data:

    {
      "data": [
      {
       "key": "A",
       "value": 310
      },
      {
       "key": "B",
       "value": 240
      },
      {
       "key": "C",
       "value": 110
      },
      {
       "key": "D",
       "value": 90
      },
      {
       "key": "E",
       "value": 60
      },
      {
       "key": "F",
       "value": 50
      },
      {
       "key": "G",
       "value": 30
      },
      {
       "key": "H",
       "value": 10
      }
     ]
    }
    

    The expression:

    data#$i[$i<5]
    

    Will return:

    [
      {
        "key": "A",
        "value": 310
      },
      {
        "key": "B",
        "value": 240
      },
      {
        "key": "C",
        "value": 110
      },
      {
        "key": "D",
        "value": 90
      },
      {
        "key": "E",
        "value": 60
      }
    ]
    

    Working example: https://try.jsonata.org/LCvBc6KT_

    Login or Signup to reply.
  2. The predicate can be a sequence of numbers (https://docs.jsonata.org/path-operators#—filter). So the following will select the first 5 items:

    data[[0..4]]

    See https://try.jsonata.org/ENUX8wkyM

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