Robin
Robin

Reputation: 109

Jolt Transformation to move an attribute in each element of the array

My Json Input is as follows

{
  "ref": "22",
  "id": "177",
  "table": [
    {
      "zn": 1,
      "stfflbisart": 10
    },
    {
      "zn": 2,
      "stfflbisart": 50
    }
  ]
}

And I want the ref field to be included in every element present in the array object

And my desired output is as below:

{
  "id": "177",
  "table": [
    {
      "zn": 1,
      "stfflbisart": 10,
      "ref": "22"
    },
    {
      "zn": 2,
      "stfflbisart": 50,
      "ref": "22"
    }
  ]
}

The Jolt spec what I tried wasn't working out.

[
  {
    "operation": "shift",
    "spec": {
      "ref": "ref",
      "table": {
        "*": {
          // simple match.  Put the value '4' in the output under the "Rating" field
          "*": "[&1].&"
        }
      }
    }
  }
]

Any help is much appreciated here.

Upvotes: 1

Views: 2025

Answers (1)

Barbaros Özhan
Barbaros Özhan

Reputation: 65105

You can use such a shift operation

[
  {
    "operation": "shift",
    "spec": {
      "id": "id",
      "table": {
        "*": {
          "*": "&2.[&1].&",
          "@(2,ref)": "&2.[&1].ref"
        }
      }
    }
  }
]

where

  • ampersand(&)s at the at end( appearing as leaves ) match substitutions for the keys where no need to repeat their names

  • array names followed by dots (table.) might also be replaced with another name such as tab. in order to rename the current array

  • those arrays are followed by .[&1] ( eg. table.[&1] ) in order to represent combining those key-value pairs into json objects while nesting them as elements for the array

  • "*" nested following "table": { "*": { represents all keys of the table array

Upvotes: 2

Related Questions