skip to Main Content

I have been trying to set key names for json array using the fields provided. I need to fetch a separate list of managers and colleagues.
Input:

{
  "employeelist": [
    {
      "employee": "test",
      "firstName": "ABC",
      "lastName": "DEF"
    },
    {
      "employee": "test1",
      "firstName": "nametest",
      "lastName": "namelast"
    }
  ],
  "manager": "test",
  "colleague": "test1"
}

Expected Output:

{
  "manager": [
    {
      "employee": "test",
      "firstName": "ABC",
      "lastName": "DEF"
    }
  ],
  "colleague": [
    {
      "employee": "test1",
      "firstName": "nametest",
      "lastName": "namelast"
    }
  ]
}

Spec I used repeats the the complete list for both managers and colleagues.

[
  { // segregate values of the same key and form respective arrays.
    "operation": "shift",
    "spec": {
      "employeelist": {
        "*": {
          "employee": {
            "@(3,manager)": {
              "@2": "manager.[]"
            },
            "@(3,colleague)": {
              "@2": "colleague.[]"
            }
          }
        }
      }
    }
  }
]

2

Answers


  1. You can use the following shift transformation spec

    [
      {
        "operation": "shift",
        "spec": {
          "employeelist": {
            "*": {
              "@": "@1,employee" // accumulate values of "manager" and "colleague" attributes with respective "employee" values under the common arrays labeled by those values 
            }
          },
          "*": {
            "$": "@(0)" // exchange the key-value pairs of the attributes "manager" and "colleague"
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": { // all newly transformed arrays
            "@1,&[0]": "@(2,&[1])[]" //match values of 0th and 1st components per each array while adding a [] suffix to convert the resultant objects nested within square brackets as desired 
          }
        }
      }
    ]
    

    where the first components([0]) of the newly derived arrays(test and test1) are matched with the second components([1]) within the last spec

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

    enter image description here

    Login or Signup to reply.
  2. I think this simpler jolt spec might achieve the expected output, but please note that it works only if the document that needs to be moved to the "manager" field is the first element of the array (that’s why it matches the 0 index), and the document of "colleague" is the second element of the array (index 1).

    [
      {
        "operation": "shift",
        "spec": {
          "employeelist": {
            "0": "manager[]",
            "1": "colleague[]"
          }
        }
      }
    ]
    

    Hope you find it useful!

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