Home > Software engineering >  JOLT: copy attributes from another array, matching by key value
JOLT: copy attributes from another array, matching by key value

Time:02-15

Given the following input json:

{
  "colleges": [
    {
      "id": 10369272,
      "name": "UNIVERSITY OF SAN DIEGO"
    },
    {
      "id": 10331208,
      "name": "UNIVERSITY OF CALIFORNIA - BERKELEY (EXTENSION)"
    },
    {
      "id": 10331207,
      "name": "SEATTLE PACIFIC UNIVERSITY"
    }
  ],
  "degrees": [
    {
      "id": 6215911,
      "type": "Bachelor of Arts",
      "collegeId": 10331207
    },
    {
      "id": 6235281,
      "type": "Bachelor of Science",
      "collegeId": 10331208
    }
  ]
}

and the desired output of:

{
  "colleges": [
    {
      "name": "UNIVERSITY OF SAN DIEGO"
    },
    {
      "name": "UNIVERSITY OF CALIFORNIA - BERKELEY (EXTENSION)",
      "degreeType": "Bachelor of Science"
    },
    {
      "name": "SEATTLE PACIFIC UNIVERSITY",
      "degreeType": "Bachelor of Arts"
    }
  ]
}

how would a JOLT spec look like to associate correct degrees with correct colleges?

In other words I need to locate a correct degree by the college id, extract its type and place it under the correct college.

Struggling to find a similar example somewhere. Any suggestion is highly appreciated.

CodePudding user response:

You can walk through the indexes of colleges array along with shift transformation

by contribution of &2[#(1)].@(1,id) identifiers in order to combine the attributes under common

collegeId ( @(1,id) and @(3,degrees[&].collegeId)) values while wrapping all set of the objects

with colleges array (@(1,&2[#(1)])) such as

[
  {
    "operation": "shift",
    "spec": {
      "colleges": {
        "*": {
          "name": "&2[#1].@(1,id).&",
          "@(2,degrees[&].type)": "&2[#].@(3,degrees[&].collegeId).degreeType"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": "&2"
        }
      }
    }
  }
]

enter image description here

  • Related