Search code examples
apache-nifijslt

How to use NiFi (1.25) JSLTTransformJSON processor to get specific fields from an array as a single entry


I have JSON input from which I want to pull out the same sub-elements of arrays into one field. Trying to figure how to structure JSLT using NiFi JSLTTransformJSON processor.

Input:

{
  "name": "John Smith",
  "ID": "123123123",
  "address": [
    {
      "location": "123 Main, Citty, ST",
      "info": {
        "type": "single family",
        "own": "yes"
      }
    },
    {
      "location": "123 Lane, Wonderland, ST",
      "info": {
        "type": "apartment",
        "own": "yes"
      }
    },
    {
      "location": "123 Street, Place, ST",
      "info": {
        "type": "condo",
        "own": "no"
      }
    }
  ]
}

Desired output:

{
  "name": "John Smith",
  "ID": "123123123",
  "residence_type": "single family, apartment, condo"
}

Desired output where the info.own == "yes" :

{
  "name": "John Smith",
  "ID": "123123123",
  "residence_type": "123 Main, Citty, ST; 123 Lane, Wonderland, ST"
}

where I don't know how many addresses there might be.


Solution

  • For the first desired output:

    {
    
      
      "residence_type":join([for (.address) .info.type],", "),
      "address":null,
      *:.
    
    }
    

    For the second desired output:

    {
    
      
      "residence_type":join([for (.address) .location if(.info.own=="yes")],", "),
      "address":null,
      *:.
    
    }
    

    If you are trying to combine both based on the info.own value:

    {
    
      
      "residence_type":join([for (.address) .location if(.info.own=="yes")]+[for (.address) .info.type if(.info.own!="yes")] ,"; "),
      "address":null,
      *:.
    
    }
    

    if you are getting the info.own as flowfile attribute you can include in the JSLT spec using Expression Language and use jslt function to drive the output:

    def residence_type(info_own)
        
        if($info_own=="yes")
        
           join([for (.address) .location if(.info.own=="yes")],"; ")
        
        else
        
           join([for (.address) .info.type],", ")
        
        
        {
        
        
          "residence_type":residence_type("${info.own}"),
          "address":null,
          *:.
        
        }
    

    Hope that helps.