Home > Software engineering >  Extract values from array w Jolt
Extract values from array w Jolt

Time:09-16

JSON:

[
  {
    "cabinetId": 3,
    "anotherId": 1,
    "positionIds": [
      1019149753,
      987654321
    ]
  },
  {
    "cabinetId": 10,
    "anotherId": 2,
    "positionIds": [
      97812316
    ]
  }
]

I want to unnest values from arrays, so I expected:

[
  {
    "cabinetId": 3,
    "anotherId": 1,
    "id": 1019149753
  },
  {
    "cabinetId": 3,
    "anotherId": 1,
    "id": 987654321
  },
  {
    "cabinetId": 10,
    "anotherId": 2,
    "id": 97812316
  }
]

Tried with:

[
 {
    "operation": "shift",
    "spec": {
      "*": {
        "positionIds": {
          "*": {
            "@": "[&1].id",
            "@(2,cabinetId)": "[&1].cabinetId"
          }
        }
      }
    }
  }
]

But now I have only arrays.

P.S. Sorry that I keep removing my config from code section. Editor throws an error and asks me to add more details.

Doesn't work with:

[
  {
    "cabinetId": 12,
    "anotherId": 11,
    "positionIds": [
      1019149753,
      987654321
    ]
  },
  {
    "cabinetId": 10,
    "anotherId": 10,
    "positionIds": [
      97812316
    ]
  },
  {
    "cabinetId": 10,
    "anotherId": 10,
    "positionIds": [
      123456789
    ]
  }
]

I receive:

[
  {
    "id": 1019149753,
    "cabinetId": 12
  },
  {
    "id": 987654321,
    "cabinetId": 12
  },
  {
    "id": [
      97812316,
      123456789
    ],
    "cabinetId": [
      10,
      10
    ]
  }
]

CodePudding user response:

You can walk through the indexes of positionIds such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "positionIds": {
          "*": {
            "@": "[&1].id",
            "@(2,cabinetId)": "[&1].cabinetId",
            "@(2,anotherId)": "[&1].anotherId"
          }
        }
      }
    }
  },
  {
    // accumulate each array within a single object 
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "@": "&"
        }
      }
    }
  },
  {
    // dissipate the values by indexes of the components within the arrays
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&].&1"
      }
    }
  }
]

the demo on the site enter image description here

  • Related