poezii siflori
poezii siflori

Reputation: 1

JOLT operations to filter struct based on keys given in string array

I have this JSON input:

{
  "input": {
    "a": "valueA",
    "b": "valueB",
    "c": "valueC"
  },
  "fieldsToFilterBy": [
    "a",
    "c"
  ]
}

and i want to have this output:

{
  "input": {
    "a": "valueA",
    "b": "valueB",
    "c": "valueC"
  },
  "filteredValues": [
    "valueA",
    "valueC"
  ]
}

How can I obtain this using JOLT operations? I've tried many ways but nothing works all the way

Upvotes: 0

Views: 35

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65313

You can use a shift transformation spec in which

  • go 3 levels up (traverse once :, and double { ) the tree in order to reach "input" object's level and .& notation to replicate the leaf nodes' values
  • rename as desired( filteredValues in this case ) on RHS

such as

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",//else case in order to replicate the "input" object
      "fieldsToFilterBy": {
        "*": {
          "*": { "@(3,input.&)": "filteredValues" }
        }
      }
    }
  }
]

the demo on the site http://jolt-demo.appspot.com/ is

enter image description here

Upvotes: 1

samsal77
samsal77

Reputation: 729

You can try the following spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "fieldsToFilterBy": {
        "*": "input.@(0)"
      }
    }
  }
  ,
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "0": {
            "@": ["&3.&2", "filteredValues[]"]
          },
          "1": {
            "": ""
          },
          "*": {
            "$": "&3.&2"
          }
        }
      }
    }
  }

]

This basically will work if ValueA,ValueB, ValueC...etc. can never be 1 or 0. If they can then it wont work and there is another way which might get little more complex.

Upvotes: 0

Related Questions