Search code examples
jsongroovy

Unable to determine current character, it is not a string, number, array or object?


Please help with the Groovy script. I am using this groovy script in apache nifi but all the inputs are Json actually and not string or Object. And I think thats why I am getting error.

I want to know how can I use json or convert json into String or object so that my code can work. The code:

**FlowFile Content **

"COVID-19"

The Response has data like this

Response
{
  "Name" : {
    "COVID-19" : [ "88" ],
    "Fever" : [ "40" ]
}
}

I want to access 88 in data1 finally and send it to ahead after execute script.

In s3data, there is varibale named SID which has same as of COVID-19, so I want to match it with flowfile content and whichever flowfile content will match it will send its id i.i 88 in this example.


Solution

  • The code to parse the JSON from text and find the desired value can look like so:

    import groovy.json.*
    
    String nameToFind = 'COVID-19'
    
    String VRResponseText = '''{ "customReasonName" : { "COVID-19" : [ "88" ], "Fever" : [ "40" ] } }'''
    
    def VRResponse = new JsonSlurper().parseText VRResponseText
    
    String desiredValue = VRResponse.customReasonName.findResult{ k, v -> k == nameToFind ? v[ 0 ] : null }
    
    assert desiredValue == '88'