How to define a transformation that doesn't require hard-coded names

Viewed 44

I have a working transformation, but it is using hard-coded property name references. I've been trying to figure out how to define a transformation that is generic but I haven't found anything that works.

My input data looks like this:

{
  "data": [
    {
      "A": 1,
      "B": "testing",
      "C": 100
    },
    {
      "A": 2,
      "B": "testing",
      "C": 200
    }
  ],
  "newVals": {
    "B": "new val",
    "C": 7
  }
}

I want to apply the values in the newVals object and apply them to the objects in the array so that the resulting data looks like this:

[
  {
    "A": 1,
    "B": "new val",
    "C": 7
  },
  {
    "A": 2,
    "B": "new val",
    "C": 7
  }
]

The transformation I have is working, but requires the property names to be hard-coded. I am trying to define a transformation that would allow any matching property name to be properly modified. So that if another data set had an property "D", with a new value in the newVals object it would be applied.

My hard-coded transformation looks like this:

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "data": {
        "*": {
          "new_B": "@(3,newVals.B)",
          "new_C": "@(3,newVals.C)"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "@(0,A)": "[#2].A",
          "@(0,new_B)": "[#2].B",
          "@(0,new_C)": "[#2].C"
        }
      }
    }
  }
]

Is there a way to write that so that in addition to the example data above it can transform this:

{
  "data": [
    {
      "A": 1,
      "E": "testing",
      "F": 100
    }
  ],
  "newVals": {
    "E": "new val",
    "F": 7
  }
}
1 Answers

For the first desired result;

Convert modify-default-beta to modify-overwrite-beta spec, this case no need need to rename the keys, eg. new_ prefixes are not needed. Meanwhile, no need to explicitly write each element, rather replace them with "*": "@(3,newVals.&)". And then just pick the objects of the data array within the shift spec such as

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "data": {
        "*": {
          "*": "@(3,newVals.&)"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "data": {
        "@": ""
      }
    }
  }
]

enter image description here

For the second desired result;

Using just one step of shift spec would be sufficient such as

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "0": {
          "A": "&2.[#2].&",
          "B": "&2.[#2].E",
          "C": "&2.[#2].F"
        }
      },
      "*": "&"
    }
  }
]

where "*": "&" is used to represent the array other than data

enter image description here

Related