Search code examples
javajsonjolt

Jolt: Convert string array into individual objects


I'm trying to convert an array of strings into objects. Which is not workings as I expected. Can someone help me with this?

I got struck by splitting the array of items into individual objects. Some of the items are forming as an array only.

Input JSON:

{
  "GroupMembers": {
    "group1": [
      "member1",
      "member2",
      "member3"
    ],
    "group2": [
      "member1",
      "member4",
      "member6",
      "member8"
    ],
    "group3": [
      "member2",
      "member6"
    ]
  }
}

My Spec File:

[
  {
    "operation": "shift",
    "spec": {
      "GroupMembers": {
        "*": {
          "*": {
            "@(1,[&])": {
              "*": {
                "$(3)": "GroupMembers[#4].groupId",
                "$": "GroupMembers[#4].memberId"
              }
            }
          }
        }
      }
    }
  }
]

and my expected output is

{
  "GroupMembers": [
    {
      "groupId": "group1",
      "memberId": "member1"
    },
    {
      "groupId": "group1",
      "memberId": "member2"
    },
    {
      "groupId": "group1",
      "memberId": "member3"
    },
    {
      "groupId": "group2",
      "memberId": "member1"
    },
       .....
       .....    
    {
      "groupId": "group3",
      "memberId": "member6"
    }
  ]
}

Solution

  • You can use the following transformation

    [
      { // form objects from array keys vs. array components
        "operation": "shift",
        "spec": {
          "GroupMembers": {
            "*": {
              "*": {
                "$1": "&3.&2.&1.groupId", // partition by top level object, array and its indexes
                "@": "&3.&2.&1.memberId"
              }
            }
          }
        }
      },
      { // collect each key-value pairs under the common array node, namely "GroupMembers"
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": "&2[]"
            }
          }
        }
      }
    ]
    

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

    enter image description here