Home > Software engineering >  Conditional shift within array with Jolt
Conditional shift within array with Jolt

Time:08-05

Thanks in advance for reading this one!

I have the following JSON:

{
  "transactions": [
    {
      "type": "wd",
      "charged": "-1000.00",
      "credited": "0"
    },
    {
      "type": "dep",
      "charged": "0",
      "credited": "1000.00"
    }
  ]
}

What I need is to keep either charged or credited, whichever one is not 0. My spec below almost has it working

[
  {
    "operation": "shift",
    "spec": {
      "transactions": {
        "*": {
          "type": "settled.[&1].transType",
          "charged": {
            "0": {
              "@(2,credited)": "settled.[&1].cash_movement"
            }
          },
          "credited": {
            "0": {
              "@(2,charged)": "settled.[&1].cash_movement"
            }
          }
        }
      }
    }
  }
]

What I want to end up with is:

{
  "settled": [
    {
      "transType": "wd",
      "cash_movement": "-1000.00"
    },
    {
      "transType": "dep",
      "cash_movement": "1000.00"
    }
  ]
}

But what I end up with is this instead:

{
  "settled": [
    {
      "transType": "wd",
      "cash_movement": ["-1000.00","1000.00"]
    },
    {
      "transType": "dep"
    }
  ]
}

I know I'm close but for the life of me, I haven't been able to tweak it to get it just right. Can someone set me in the right direction please?

CodePudding user response:

Just need to convert the identifiers [&1] to [&3] except for the first one such as

[
  {
    "operation": "shift",
    "spec": {
      "transactions": {
        "*": {
          "type": "settled[&1].transType",
          "charged": {
            "0": {
              "@(2,credited)": "settled[&3].cash_movement"
            }
          },
          "credited": {
            "0": {
              "@(2,charged)": "settled[&3].cash_movement"
            }
          }
        }
      }
    }
  }
]

since twice more going the tree up needed for those innermost pairs in order to reach the same level with the first [&1]. Btw, the dots between settled and [&.]s are redundant to be used.

the demo on the site enter image description here

  • Related