Search code examples
jsontransformationjolt

Jolt alternative for head to find first non empty non null string in json array


Is there any alternative head to transform and get first non empty or non null value from JSON array. similar to head(/part/subline/sublineGrouop/sublineGroupTP/detailsGP/dtlLine/details/code) should return US

{
  "part": {
    "subline": {
      "sublineGroup": {
        "property1": "test",
        "proerty2": "tes2",
        "sublineGroupTP": {
          "detailsGP": [
            {
              "dtlLine": {
                "details": {
                  "code": null
                }
              }
            },
            {
              "dtlLine": {
                "details": {
                  "code": ""
                }
              }
            },
            {
              "dtlLine": {
                "details": {
                  "code": "US"
                }
              }
            },
            {
              "dtlLine": {
                "details": {
                  "code": "UK"
                }
              }
            }
          ]
        }
      }
    }
  }
}

Expected Output JSON

{
  "countryCode": "US"
}

Solution

  • An option is to write the whole path(s) preceded by @ sign, except for the parts with arrays, in which you might use a conditional in order to get an array with non-null and non-blank components, then pick the first components of the array by the function such as

    [
      {
        "operation": "shift",
        "spec": {
          "@part.subline.sublineGroup.sublineGroupTP.detailsGP": {
            "*": { // the indexes of the "detailsGP" array
              "@dtlLine.details.code": { // the conditional for the code values starts here
                "": "", // blank values
                "*": {  // values with length > 0
                  "$": "countryCode[]" // current key values which are the values 
                                       // arraywisely( [] ) inherited from the upper node, 
                                       // eg. the values of codes
                }
              }
            }
          }
        }
      },
      { // in order to pick the first component from the array
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": "=firstElement(@(1,&))" // derive the value of the array( & ) 
                                       // from the current right-hand-side( 1 ) level
        }
      }
    ]