4

In JMESPath with this query:

people[].{"index":@.index,"name":name, "state":state.name}

On this example data:

{
  "people": [
    {
      "name": "a",
      "state": {"name": "up"}
    },
    {
      "name": "b",
      "state": {"name": "down"}
    },
    {
      "name": "c",
      "state": {"name": "up"}
    }
  ]
}

I get:

[
  {
    "index": null,
    "name": "a",
    "state": "up"
  },
  {
    "index": null,
    "name": "b",
    "state": "down"
  },
  {
    "index": null,
     "name": "c",
     "state": "up"
  }
]

How do I get the index property to actually have the index of the array? I realize that @.index is not the correct syntax but have not been able to find a function that would return the index. Is there a way to include the current array index?

dreftymac
  • 31,404
  • 26
  • 119
  • 182

2 Answers2

3

Use-case

  • Use Jmespath query syntax to extract the numeric index of the current array element, from a series of array elements.

Pitfalls

  • As of this writing (2019-03-22) this feature is not a part of the standard Jmespath specification.

Workaround

  • This is possible when running Jmespath from within any of various programming languages, however this must be done outside of Jmespath.
dreftymac
  • 31,404
  • 26
  • 119
  • 182
1

This is not exactly the form you requested but I have a possible answer for you:

people[].{"name":name, "state":state.name} | merge({count: length(@)}, @[*])

this request give this result:

{
  "0": {
    "name": "a",
    "state": "up"
  },
  "1": {
    "name": "b",
    "state": "down"
  },
  "2": {
    "name": "c",
    "state": "up"
  },
  "count": 3
}

So each attribute of this object have a index except the last one count it just refer the number of attribute, so if you want to browse the attribute of the object with a loop for example you can do it because you know that the attribute count give the number of attribute to browse.

bosskay972
  • 890
  • 1
  • 6
  • 27
  • 1
    which jmespath implementation did you use to come up with this? When I test with https://github.com/jmespath/jmespath.terminal, the result is `{"count": 3, "name": "state"}` – harschware Sep 15 '20 at 17:21