Execute Script ProcessSession.read has not been closed
Hi, I am trying ro read from a json file and create flowfiles with the kews as attributes and one flowfile per value in the list.
The json file looks something like this:
{
"key1": null,
"key2": null,
"list": ["foo", "bar"],
"key3": 1
}
This is my execute script:
import json
import java.io
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback
from org.apache.nifi.processor.io import InputStreamCallback
flowFile = session.get()
if (flowFile != None):
stream_content = session.read(flowFile)
text_content = IOUtils.toString(stream_content, StandardCharsets.UTF_8)
json_data = json.loads(text_content)
for i in json_data["list"]:
flowFile2 = session.create()
flowFile2 = session.putAttribute(flowFile2, "key3", str(json_data["key3"]))
flowFile2 = session.putAttribute(flowFile2, "key1", json_data["key1"])
flowFile2 = session.putAttribute(flowFile2, "list_value", i)
session.transfer(flowFile2, REL_SUCCESS)
session.remove(flowFile)
Now I keep getting an error that I need to close the process session first because my original flowfile is still in use. How can I iterate over the list to create multiple flowfiles properly? I couldn't find any similar case or example of this sort. Thanks for tips and help.
Edit: So I changed my code to create a dictionnary in order to use a new variable name for each flowfile created, but now I keep getting a key error when I want to transfer them to the success relationship.
import json
import java.io
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback
from org.apache.nifi.processor.io import InputStreamCallback
flowFile = session.get()
if (flowFile != None):
stream_content = session.read(flowFile)
text_content = IOUtils.toString(stream_content, StandardCharsets.UTF_8)
json_data = json.loads(text_content)
d = {}
for x in range(len(json_data["list"])):
d["flowfile{0}".format(x)] = json_data['list'][x]
for file in d:
file = session.create()
file = session.putAttribute(file, "key3", str(json_data["key3"]))
file = session.putAttribute(file, "key2", json_data["key2"])
file = session.putAttribute(file, "list_value", d[file])
session.transfer(file, REL_SUCCESS)
session.remove(flowFile)

