I have a json data incoming and I use ExecuteScript with Python code to extract key and value of this json data then put them into Attribute. Here my code:
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
class StreamCallback(StreamCallback):
def __init__(self):
pass
def process(self, inputStream, outputStream):
text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
data = json.loads(text)
for key in data:
first = key
break
content = data[first]
viewFlowFile = session.create()
viewFlowFile = session.putAllAttributes(viewFlowFile,{'project': str(first), 'content': str(content)})
session.transfer(viewFlowFile, REL_SUCCESS)
flowFile = session.get()
if flowFile != None:
flowFile = session.write(flowFile, StreamCallback())
session.transfer(flowFile, REL_FAILURE)
session.commit()
When I run Job ExecuteScript returns string with prefix 'u'.
My input:
{ "project_1": { "device_code": "V001", "line_code": "Anodiziing 12L"}}
and the output of content Attribute:
{ u'device_code': u'V001', u'line_code': u'Anodiziing 12L'}
I also tried add
#!/usr/bin/python3
on header of body code. But there is no change.
My question is how to return string correctly without prefix 'u' using ExecuteScript Nifi?
Updated:
We need convert type of data from dictionary to string.
Using json.dumps(content)
instead of str(content)
and output will have no prefix 'u'.
JSON strings are Unicode. The u'' is just an indicator that the dictionary you are printing contains Unicode strings. If you don't want to see them, print the strings directly. If you were running Python 3, it doesn't use u'' for Unicode strings, as they are the default, but you would see b'' for byte strings.