skip to Main Content

I am using JOLT to transform a JSON array to JSON array but flattening the inner string array list. Below is the input, expected output and JOLT used for generating the data.

[
  {
    "name": "St",
    "Subjects": [ "A1" , "A2"]
  },
  {
    "name": "MD",
    "Subjects": [ "B1" , "B2", "B4"]
  }
]

I am using JOLT transformation to generate the following output – which is still an array – but the nested string array is flattened.

[
  {
    "name": "St",
    "Subject": "A1"
  },
  {
    "name": "St",
    "Subject": "A2"
  },
  {
    "name": "MD",
    "Subject": "B1"
  },
  {
    "name": "MD",
    "Subject": "B2"
  },
  {
    "name": "MD",
    "Subject": "B4"
  }
]

I have build this JOLT but its not producing the desired results.

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "name": "[&1].name",
        "Subjects": {
          "*": {
            "*": {
              "$": "[&1].Subject"
            }
          }
        }
      }
    }
  }
]

The subject information does not show up on the result data. I have used [&1]. Subject to split the subject to multiple but the output produced is not having any Subject. I am fairly new to JOLT and help with the syntax would be appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    Just adding an improvised version of the above answer, so that JOLT newbie's like me can understand a few more concepts.

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "Subjects": {
              "*": {
                "@2,name": "&3.&1.name", // go 2 levels up the tree to grab the related value
                "@": "&3.&1.subject"
              }
            }
          }
        }
      },
      { // get rid of object keys
        "operation": "shift",
        "spec": {
          "*": {`enter code here`
            "*": ""
          }
        }
      }
    ]
    

  2. You can loop through within the Subjects arrays while grabbing the values of name attribute from the same level such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "Subjects": {
              "*": {
                "@2,name": "&3.&1.name", // go 2 levels up the tree to grab the related value
                "@": "&3.&1.&2"
              }
            }
          }
        }
      },
      { // get rid of object keys
        "operation": "shift",
        "spec": {
          "*": {
            "*": ""
          }
        }
      }
    ]
    

    where

    • &3s represent the indexes of the objects within the main array,
    • &1s represent the indexes of the Subjects array

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

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search