user7516956
user7516956

Reputation:

NIFI:Json Content Parsing in FlowFile

I have text attribute in GenerateFlowfile processor like this:

[{
  "status": {
    "runStatus": "STOPPED"
  },
  "component": {
    "state": "STOPPED",
    "id": "ea5db028-015d-1000-5ad5-80fd006dda92"
  },

  "revision": {
    "version": 46,
    "clientId": "ef592126-015d-1000-bf4f-93c7cf7eedc0"
  }
} ]

and related groovy script in my ExecuteScript processor :

import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
    return;
}

def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>

session.read(flowFile,
    { inputStream ->
        def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
        text=flowFile.getAttribute('text')
        def obj = slurper.parseText(text)

        obj.each {k,v ->
           attrs[k] = v.toString()
        }
    } as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)

but my processor still shows me exception like this, what should i change? enter image description here

Upvotes: 2

Views: 2797

Answers (1)

daggett
daggett

Reputation: 28644

the problem that the root element of your json is an array

and you try to iterate it like map .each{k,v-> ... }

probably you want to take the first map to iterate it like in code below

def obj=[ [a:1] ]

//this line will throw exception:
//obj.each{k,v-> println "$k->$v" }

//but this one not
obj[0].each{k,v-> println "$k->$v" }

fyi: there is a EvaluateJsonPath processor that could extract attributes from json flowfile content and put result into attribute

Upvotes: 2

Related Questions