Search code examples
jsonjmespath

How do I access certain elements with jmespath using slicing?


I have the following JSON

{
    "items": [
        {
            "configurationStatus": "SYNCED",
            "conflictDetectionState": "IN_SYNC",
            "connectivityState": "ONLINE",

I can access individual elements inside with items[*].isModel, but, I cannot figure out how to access the first 3 elements. I tried something like this items[*].[0:2], but it didn't work. I am curious how to access the first 3 elements using slicing.


Solution

  • You would possibly face some issue trying to achieve this because, as pointed in the JMESPath documentation, object are:

    object (an unordered collection of key value pairs)

    Source: https://jmespath.org/specification.html, emphasis, mine

    So you might end up with different keys based on the implementation and have really random results.


    Now the issue with your approach is that slices can only act on arrays.

    A slice expression allows you to select a contiguous subset of an array.

    Source: https://jmespath.org/specification.html#slices, emphasis, mine

    What you could do then, in order to have an array out of a hash is to use the values function, but mind that you'll lose the key/value association in the process.
    Then, given you have an array, you can now apply the slicing technique.

    So with the query:

    items[].values(@)[0:3]
    

    On the JSON:

    {
        "items": [
            {
                "configurationStatus": "SYNCED",
                "conflictDetectionState": "IN_SYNC",
                "connectivityState": "ONLINE",
                "foo": "bar",
                "baz": "qux"
            },
            {
                "configurationStatus": "SYNCED′",
                "conflictDetectionState": "IN_SYNC′",
                "connectivityState": "ONLINE′",
                "foo": "bar′",
                "baz": "qux′"
            }
        ]
    }
    

    This would give:

    [
      [
        "SYNCED",
        "IN_SYNC",
        "ONLINE"
      ],
      [
        "SYNCED′",
        "IN_SYNC′",
        "ONLINE′"
      ]
    ]