Search code examples
jsonjolt

Jolt Transform add object to array


I'm facing an issue with implementing Jolt Spec to transform this input.

input:

{
  "id": 12345,
  "category": 2,
  "productAttributes": {
    "data": [
      {
        "name": "Size",
        "slug": "size",
        "value": "10"
      },
      {
        "name": "Color",
        "slug": "color",
        "value": "Grey"
      }
    ]
  }
}

spec:

[
  {
    "operation": "shift",
    "spec": {
      "productAttributes": {
        "data": {
          "*": {
            "slug": "attributes[#2].key",
            "value": "attributes[#2].value",
            "name": "attributes[#2].name"
          }
        }
      }
    }
  }
]

desired output:

{
  "attributes": [
    {
      "key": "size",
      "value": "10",
      "name": "Size"
    },
    {
      "key": "color",
      "value": "Grey",
      "name": "Color"
    },
    {
      "key": "category",
      "value": "2",
      "name": "Category"
    }
  ]
}

I want to add the category in root to the attributes array. The value will be taken from the category property. key and name will be filled as static.

Could you help me? Thanks.


Solution

  • You can use

    • a&(3,1)(or a&(2,1)) identifier, which replicates the 1st asterisk after going 3 or 2 levels going up the tree, in order to keep the common literal ttributes along with the object that will be added

    • # wildcards to hardcode a literal

    So, the needed transformation will be

    [
      {
        "operation": "shift",
        "spec": {
          "productA*": {
            "data": {
              "*": {
                "slug": "a&(3,1).&1.key",
                "*": "a&(3,1).&1.&"
              },
              "#category": "a&(2,1).&1.key",
              "@2,category": "a&(2,1).&1.value",
              "#Category": "a&(2,1).&1.name"
            }
          }
        }
      },
      { //convert to array of obects
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": "[#2].&"
            }
          }
        }
      },
      { //make all "value"s quoted
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "*": "=toString"
          }
        }
      }
    ]
    

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

    enter image description here