JSON split batch #5830
-
Hello, My question is, how do I call/reference the incoming message in JavaScript, so that I can then parse it. Assuming I can parse it using a forEach. I tried calling 'msg' but at the source connector level 'msg' is not defined yet. I'm just not sure how to call the inbound message. Attached a sample JSON with just 2 trials. The actual results has around 700. I need each trial under the DATA object to be a separate message. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 6 replies
-
It is just an object, so you can reference it via msg: function convertToCSV(jsonData) {
const header = jsonData.COLUMNS.join(",");
const rows = jsonData.DATA.map(row => row.join(","));
return header + "\n" + rows.join("\n");
}
// Convert JSON to CSV
var csvData = convertToCSV(msg);
// csvData will have your JSON as CSV. Point is you can use array prototype methods to parse the data, you may not need to batch split it. |
Beta Was this translation helpful? Give feedback.
-
Was able to tweak the code so the columns map to the data objects. var queue = $gc('queue');
if (!queue) {
queue = new java.util.LinkedList();
var obj = JSON.parse(org.apache.commons.io.IOUtils.toString(reader));
for each (var row in obj.DATA) {
var rowObj = {};
for (var i = 0; i < obj.COLUMNS.length; i++) {
rowObj[obj.COLUMNS[i]] = row[i];
}
queue.add(JSON.stringify(rowObj));
}
$gc('queue', queue);
}
var message = queue.poll();
if (!message) {
globalChannelMap.remove('queue');
}
return message; |
Beta Was this translation helpful? Give feedback.
-
Here's a more modern update to the code in #5830 (comment). It uses the same idea as #5830 (reply in thread), but replaces the var stack = $gc('stack')
if (!stack) {
const doc = JSON.parse(org.apache.commons.io.IOUtils.toString(reader))
const rowToJSON = row => JSON.stringify(doc.COLUMNS.reduce((obj,colName,i) => (obj[colName] = row[i], obj), {}))
stack = doc.DATA.map(rowToJSON).reverse()
$gc('stack', stack)
}
const message = stack.pop() || null
if (!message) {
globalChannelMap.remove('stack')
}
return message You didn't mention how you are getting or processing your messages, but be aware that this solution is intended for single-threaded operation. |
Beta Was this translation helpful? Give feedback.
-
Closing - but @tonygermano 's answer is probably the most intuitive one these days. |
Beta Was this translation helpful? Give feedback.
Your JSON example file is not valid JSON, you have an extra comma at the end, please take the time to make sure sample files you post are correct.
Put this code in the splitter whiich is almost verbatim from a post by @narupley at the forums, please do check there in the future.