Home > Software design >  Jolt transform several object to array with new field name
Jolt transform several object to array with new field name

Time:12-16

I'am new using jolt tool and i wonder if there a way to take several json objects and put them to an array with a new field named as follows:

Input :

{
  "userId": 1,
  "age": 20,
  "desc1": "value desc1",
  "desc2": "value desc2",
  "desc3": "value desc3"
}

JSON spec :

[
  {
    "operation": "shift",
    "spec": {
      "userId": "ID",
      "age": "age",
      "*": "additionalInformation"
    }
  }
]

Expected result :

{
  "ID": 1,
  "age": 20,
  "additionalInformation": [
    {
      "code": "desc1",
      "value": "value desc1"
    },
    {
      "code": "desc2",
      "value": "value desc2"
    },
    {
      "code": "desc3",
      "value": "value desc3"
    }
  ]
}

Using the spec above i can only obtain this result :

{
  "ID": 1,
  "test": 20,
  "additionalInformation": [
    "value desc1",
    "value desc2",
    "value desc3"
  ]
}

Any suggestion what i have missed ?

CodePudding user response:

You can use $ and @ wildcards for code and value, respectively while combining the elements under common factor by using &. as prefixes for them in the first step. Then combine elements other than ID and age within the same array in the last step such as

[
  {
    "operation": "shift",
    "spec": {
      "userId": "ID",
      "age": "age",
      "*": {
        "$": "&.code",
        "@": "&.value"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "ID": "&",
      "age": "&",
      "*": "additionalInformation[]"
    }
  }
]

enter image description here

Edit(due to the comment) : If you need to pick some individual elements such as desc1 and desc3 rather than all("*"), then replace the first spec with following

  {
    "operation": "shift",
    "spec": {
      "userId": "ID",
      "age": "age",
      "desc1|desc3": {
        "$": "&.code",
        "@": "&.value"
      }
    }
  }
  • Related