Search code examples
arraysjsonapache-nifitransformationjolt

JOLT transformation add the same elements into all arrays


I want to add the same values to every element of an array. My approach is to use default to add the value. It is a litte bit different from this one, because: I don't know how to write into an existing element of the array instead of a new one.

Input:

{
  "counterTop": {
    "loaf1": [
      {
        "type": "white",
        "unit": "mm",
        "test": "correct"
      },
      {
        "type": "black",
        "unit": "cm",
        "test": "false"
      }
    ]
  }
}

Specs:

[
  {
    "operation": "default",
    "spec": {
      "counterTop": {
        "loaf1": {
          "*": {
            "slices": ""
          }
        }
      }
    }
  }
]

Expected output:

{
  "counterTop": {
    "loaf1": [
      {
        "type": "white",
        "unit": "mm",
        "test": "correct",
        "slices": ""
      },
      {
        "type": "black",
        "unit": "cm",
        "test": "false",
        "slices": ""
      }
    ]
  }
}

Current output

{
  "counterTop": {
    "loaf1": [
      {
        "type": "white",
        "unit": "mm",
        "test": "correct"
      },
      {
        "type": "black",
        "unit": "cm",
        "test": "false"
      }
    ]
  }
}

Does anyone here have a solution? Outside the array it works without problems, but I can't get in there.

Thanks in advance!


Solution

  • One option would be applying shift transformation twice; in order to extract key-value pairs of the list(loaf1) by going innermost level while adding new key-value pair("slices":" ") within the first step, and then combining all lists back to the original within the second one such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": {
                "*": "&",
                "# ": "slices"
              }
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": "counterTop.loaf1[&].&1"
          }
        }
      }
    ]