-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathnested_json_to_string_transform.py
61 lines (52 loc) · 1.86 KB
/
nested_json_to_string_transform.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
###############################################################################
# Sample to transform a flowfile with nested json format to string format
# modified from "https://github.com/BatchIQ/nifi-scripting-samples"
#
# Assumed nested input json format:
#
# {
# "timestamp": 1514541007050,
# "values":[
# {
# "name": "first",
# "value": 12345,
# "message": "Foo",
# "timestamp": 151454100705
# },
# { "name": "second",
# "value": 54321,
# "message": "Qoo",
# "timestamp": 151454188888
# }]
# }
# output:
# first,12345,Foo,1514541007050
# second,54321,Qoo,151454188888
###############################################################################
import json
import sys
import traceback
from java.nio.charset import StandardCharsets
from org.apache.commons.io import IOUtils
from org.apache.nifi.processor.io import StreamCallback
from org.python.core.util import StringUtil
class TransformCallback(StreamCallback):
def __init__(self):
pass
def process(self, inputStream, outputStream):
try:
# Read input FlowFile content
input_text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
input_obj = json.loads(input_text)
for value in input_obj['values']:
output_text = "{},{},{},{}".format(value['name'],value['value'],value['message'],value['timestamp'])
outputStream.write(bytearray(output_text.encode('utf-8')))
outputStream.write(bytearray('\n'.encode('utf-8')))
except:
traceback.print_exc(file=sys.stdout)
raise
flowFile = session.get()
if flowFile != None:
flowFile = session.write(flowFile, TransformCallback())
# Finish by transferring the FlowFile to an output relationship
session.transfer(flowFile, REL_SUCCESS)