Dynamo_7587
Dynamo_7587

Reputation: 1

Need JOLT spec for array input JSON

I am working on transforming a complex json using JOLT.

Input JSON:

    { "data":
     [ 
      { 
       "fieldname": "Name", 
       "fieldvalue": [ "John Doe" ] 
    },
     { "fieldname": "Title", 
    "fieldvalue": [ "Manager" ] 
    }, 
    { "fieldname": "Company", 
    "fieldvalue": [ "Walmart" ] 
    }
    ] }
    

Expected Output:

    { 
    "finalPayload":{ 
    "PI":{ 
    "EmpName":"John Doe", 
    "EmpRole":"Manager" 
    }, 
    "Company":"Walmart"
     } 
    }
    

I am unable to understand how to access and assign "fieldvalue" in output based on "fieldname". Please help me with the JOLT spec.

Note: The order of name, title and company in input JSON will be jumbled and random meaning its not mandatory that under "data" array first object will be related to "Name" only.

Upvotes: 0

Views: 111

Answers (2)

Raymond Choi
Raymond Choi

Reputation: 1271

May I introduce an alternative library to solve the issue.

https://github.com/octomix/josson

implementation 'com.octomix.josson:josson:1.3.21'

-------------------------------------------------

Josson josson = Josson.fromJsonString(
    "{\"data\":[{\"fieldname\":\"Name\",\"fieldvalue\":[\"JohnDoe\"]},{\"fieldname\":\"Title\",\"fieldvalue\":[\"Manager\"]},{\"fieldname\":\"Company\",\"fieldvalue\":[\"Walmart\"]}]}");

JsonNode node = josson.getNode(
    "map(" +
    "  finalPayload: map(" +
    "    PI: map(" +
    "      EmpName: data[fieldname='Name'].fieldvalue[0]," +
    "      EmpRole: data[fieldname='Title'].fieldvalue[0]" +
    "    )," +
    "    Company: data[fieldname='Company'].fieldvalue[0]" +
    "  )" +
    ")");
System.out.println(node.toPrettyString());

Output

{
  "finalPayload" : {
    "PI" : {
      "EmpName" : "JohnDoe",
      "EmpRole" : "Manager"
    },
    "Company" : "Walmart"
  }
}

Upvotes: 0

Arnold Joseph
Arnold Joseph

Reputation: 545

Hi hope this helps you in resolving your issue. You can have condition in Jolt too, by going inside the variable and checking the fieldname.

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "fieldname": {
            "Name": {
              "@(2,fieldvalue)": "finalPayload.PI.EmpName"
            },
            "Title": {
              "@(2,fieldvalue)": "finalPayload.PI.EmpRole"
            },
            "Company": {
              "@(2,fieldvalue)": "finalPayload.Company"
            }
          }
        }
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "finalPayload": {
        "PI": {
          "EmpName": "ONE",
          "EmpRole": "ONE"
        },
        "Company": "ONE"
      }
    }
  }
  ]

Upvotes: 1

Related Questions