0

currently trying to filter a JSON object and preserve the original schema using JMESPath but am having some trouble.

Within my file exists an object like so:

{
  "names": {
    "1": {
      "id": "1",
      "name": "a"
    },
    "2": {
      "id": "2",
      "name": "b"
    },
    "3": {
      "id": "3",
      "name": "c"
    },
    "4": {
      "id": "4",
      "name": "d"
    }
  }
}

When applying a filter projection, I convert it to a JSON array then apply a filter (since a filter expression is only defined for a JSON array). ex. @.{names:names.*|[?id<='2']} Which results in a JSON array:

{
  "names": [
    {
      "id": "1",
      "name": "a"
    },
    {
      "id": "2",
      "name": "b"
    }
  ]
}

Is there an alternative way to write my query to filter and get the desired result, preserving the original schema structure?

or

Does JMESPath allow for a way to change this JSON array back to a JSON object with specific key-values (key is the id of the object within) after the filter projection?

i.e. I would like my final result to match the original schema structure:

{
  "names": {
    "1": {
      "id": "1",
      "name": "a"
    },
    "2": {
      "id": "2",
      "name": "b"
    }
  }
}

I've tried scouring over the JMESPath specs but have had no success finding any built-in functions to achieve this list->object conversion with specific key names pulling from the object within.

Please let me know if what I would like to get as my output is possible using JMESPath.

tsvng
  • 1
  • I don't think it is possible, filtering projection have to happen on an array, and the downside of applying an object projection is that you are loosing the keys of the object. Plus, there is no way to generate keys from a variable, so, with all this, your requirement seems more likely to not be achievable. – β.εηοιτ.βε Feb 23 '23 at 16:38

0 Answers0