Search code examples
jsonjolt

How to add fields to nested JSON input structure


How to add fields to this nested structure? Also How to use a condition for overwrite operation?

In the provided JSON add srcDo value as sos under postalAddress object in jolt

Input :

{
  "ewc":true,
  "PartyPostalAddress": {
    "item": [
      {
        "BlBdrCd": {
          "addrTyp": "N"
        },
        "LNCd": {
          "addrTyp": "N"
        },
        "PostalAddress": {
          "SrcAddrLn1": "1 KWN",
          "SrcAddrLn2": "Second Floor",
          "SrcAddrLn3": "1569 WQAS Blvd"
        }
      }
    ]
  },
  "SrcDo": "N"
}

Expected :

{
  "PartyPostalAddress": {
    "item": [
      {
        "LNCd": {
          "addrTyp": "N"
        },
        "PostalAddress": {
          "sos":"N"
          "SrcAddrLn1": "1 KWN",
          "SrcAddrLn2": "Second Floor",
          "SrcAddrLn3": "1569 WQAS Blvd"
          
        }
      }
    ]
  }
}

Solution

  • You can add such an attribute through use of a modify spec in which a key-value pair such as

    "sos": "=(@(<int>,SrcDo))"

    would be needed, where <int> should be determined by counting the layers to traversed to reach from the new location of the attribute to its original location ( a : and four { should be traversed, hence the value of the <int> should be 5 )

    Then remove the attributes those you don't need such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "PartyPostalAddress": {
            "item": {
              "*": { //represents to indexes of the "item" array 
                     //unlike to an object nesting case
                "PostalAddress": {
                  "sos": "=(@(5,SrcDo))"
                }
              }
            }
          }
        }
      },
      { //remove undesired elements
        "operation": "remove",
        "spec": {
          "PartyPostalAddress": {
            "item": {
              "*": {
                "BlBdrCd": ""
              }
            }
          },
          "ewc|SrcDo": ""
        }
      }
    ]
    

    Alternatively you can use a shift transformation spec such as

    [
      {
        "operation": "shift",
        "spec": {
          "PartyPostalAddress": {
            "item": {
              "*": {
                "LNCd": "&3.&2[&1].&",
                "PostalAddress": {
                  "@(4,SrcDo)": "&4.&3[&2].&1.sos",
                  "*": "&4.&3[&2].&1.&" //all attributes within the "PostalAddress" object
                }
              }
            }
          }
        }
      }
    ]