Mirth Community

Mirth Community (http://www.mirthcorp.com/community/forums/index.php)
-   Support (http://www.mirthcorp.com/community/forums/forumdisplay.php?f=6)
-   -   CSV into JSON ! (http://www.mirthcorp.com/community/forums/showthread.php?t=219074)

gojoshi 04-05-2019 08:42 AM

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:
Monday,Apples;Oranges;Peaches;Mangoes,
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!

schillert 04-08-2019 01:27 AM

Hi,

here is a rather pedestrian approach which works.
I'm just writing the JSON object into a string.
Code:

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) {
                tmp+='"Fruits":[{"Fruit'+(num-1).toString()+'":"'+msg['row']['column'+num.toString()].toString()+'"';
        } else {
                tmp+=',"Fruit'+(num-1).toString()+'":"'+msg['row']['column'+num.toString()].toString()+'"';
        }
        if(num==numCols) {
                tmp += "}]}"
        }

}
msg=tmp;

Perhaps somebody can do it more elegantly....

agermano 04-08-2019 12:44 PM

I would normally expect the JSON to look like this:
Code:

{
  "Day": "Monday",
  "Fruits": ["Apples", "Oranges", "Peaches", "Mangoes"]
}

That would be produced by this code:
Code:

msg = {
    Day: msg.row.child(0).toString(),
    Fruits: msg.row.child(1).toString().split(';')
}

This will output JSON like you described:
Code:

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}, {})]
}



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

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