fraylove
fraylove

Reputation: 21

JOLT Transformation Merge Array of multi Objects

I am trying to create a jolt transformation for the below input;

{
  "group": [
    {
      "schema": "file"
    },
    {
      "key1": "val1",
      "key2": "val2"
    },
    {
      "schema": "folder"
    },
    {
      "key1": "val1",
      "key2": "val2"
    },
    {
      "schema": "dir"
    },
    {
      "key1": "val1",
      "key2": "val2"
    },
    .....more
  ]
}

With the desired output of;

{
  "group": [
  {
    "schema": "file",
    "key1": "val1",
    "key2": "val2"
  },
  {
    "schema": "folder",
    "key1": "val1",
    "key2": "val2"
  },
  {
    "schema": "dir",
    "key1": "val1",
    "key2": "val2"
  },
  .....more
]
}

The key 'schema' will always be present but I won't know what the key1,key2,etc values are. So I can't explicitly map them. Any help would be much appreciated!

Upvotes: 2

Views: 923

Answers (2)

Raymond Choi
Raymond Choi

Reputation: 1273

This solution works for any number of key values.

https://github.com/octomix/josson

Deserialization

Josson josson = Josson.fromJsonString(
    "{" +
    "  \"group\": [" +
    "    {" +
    "      \"schema\": \"file\"" +
    "    }," +
    "    {" +
    "      \"key1\": \"val1\"," +
    "      \"key2\": \"val2\"" +
    "    }," +
    "    {" +
    "      \"schema\": \"folder\"" +
    "    }," +
    "    {" +
    "      \"key1\": \"val1\"," +
    "      \"key2\": \"val2\"," +
    "      \"key3\": \"val3\"" +
    "    }," +
    "    {" +
    "      \"schema\": \"dir\"" +
    "    }," +
    "    {" +
    "      \"key1\": \"val1\"," +
    "      \"key2\": \"val2\"," +
    "      \"key3\": \"val3\"," +
    "      \"key4\": \"val4\"" +
    "    }" +
    "  ]" +
    "}");

Transformation

JsonNode node = josson.getNode(
    "group" +
    ".group(#.floor(calc(?/2)))@" +
    ".mergeObjects(elements)" +
    ".@toObject('group')");
System.out.println(node.toPrettyString());

Output

{
  "group" : [ {
    "schema" : "file",
    "key1" : "val1",
    "key2" : "val2"
  }, {
    "schema" : "folder",
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3"
  }, {
    "schema" : "dir",
    "key1" : "val1",
    "key2" : "val2",
    "key3" : "val3",
    "key4" : "val4"
  } ]
}

Upvotes: 0

Barbaros Özhan
Barbaros Özhan

Reputation: 65105

You can use successive shift transformations such as

[
//to get three independent arrays with key names : `schema`, `key1`, `key2`
//nested within an object named `group`
  {
    "operation": "shift",
    "spec": {
      "group": {
        "*": {
          "*": "&2.&"
        }
      }
    }
  },
//dissipate each key-value pairs due to corresponding positions of each element 
//within each array 
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": "&2[&].&1"
        }
      }
    }
  }
]

enter image description here

Upvotes: 1

Related Questions