web stats
CSV into JSON ! - Mirth Community

Go Back   Mirth Community > Mirth Connect > Support

Thread Tools Display Modes
Old 04-05-2019, 08:42 AM
gojoshi gojoshi is offline
OBX.2 Kenobi
Join Date: Jul 2013
Posts: 51
gojoshi is on a distinguished road
Default CSV into JSON !

Hi All,

I need to turn a csv message into JSON. What I'm stuck with is the repeating values in the CSV that need to be turned into repeating values in the JSON.
For example, the below CSV:
Needs to be turned into the below JSON:
"Day": "Monday",
"Fruits": [{"Fruit1":"Apples","Fruit2":"Oranges","Fruit3":"Pe aches", "Fruit4":"Mangoes"}]

Any help would be greatly appreciated!
Reply With Quote
Old 04-08-2019, 01:27 AM
schillert schillert is offline
OBX.1 Kenobi
Join Date: Jul 2012
Posts: 31
schillert is on a distinguished road


here is a rather pedestrian approach which works.
I'm just writing the JSON object into a string.
tmp = "";
var numCols=msg["row"].children().length();
for each (seg in msg["row"].children()) {
	var num = parseInt(seg.name().toString().replace(/column/,""),10);
	if (num==1) {
		tmp += '{"Day":"'+msg['row']['column1'].toString()+'",';
	} else if(num==2) {
	} else {
	if(num==numCols) {
		tmp += "}]}"

Perhaps somebody can do it more elegantly....
Reply With Quote
Old 04-08-2019, 12:44 PM
agermano agermano is offline
Mirth Guru
Join Date: Apr 2017
Location: Indiana, USA
Posts: 1,176
agermano is on a distinguished road

I would normally expect the JSON to look like this:
  "Day": "Monday",
  "Fruits": ["Apples", "Oranges", "Peaches", "Mangoes"]
That would be produced by this code:
msg = {
    Day: msg.row.child(0).toString(),
    Fruits: msg.row.child(1).toString().split(';')
This will output JSON like you described:
msg = {
    Day: msg.row.child(0).toString(),
    Fruits: [msg.row.child(1).toString().split(';').reduce(function(obj, fruit, i) {obj['Fruit'+(i+1)] = fruit; return obj}, {})]
Reply With Quote

csv, interate, json, loop

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

All times are GMT -8. The time now is 10:12 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2020, vBulletin Solutions, Inc.
Mirth Corporation