HL7 to JSON Parser



I have created a function that will parse the HL7 message and format it for JSON output. I am currently using this in our Open Data stream environment to clean the data and shape it. This way everything that is being output to ELK is tagged properly for all segments of the Hl7 message After trying to mess around with some of the built in pieces of the HL7.segments and stringify that. I thought I was close. But I couldn’t seem to get it to format correctly. So I decided to build a function that will do this work for me.(May have reinvented the wheel on this but making triggers is fun, Let’s be real.)

  var msg = "";
    //Routine to expose full HL7 message.  Use with caution, as it will likely expose PHI.
    function full_msg(segs) {
        if( msg == '' ){
           //tags the begininng of the JSON string for ODS ELK stack parser.
            msg = '{"eh_event":"HL7",'
            //starts a loop to pull out all of the segments present in this HL7 message
            for( i=0; i< segs.length; i++ ){
                //starts to format the object as "segmentX":
                msg += '"'+segs[i].name + '":';
                    if (segs[i].fields.length > 0) {
                        //adds [ to start array for parent object segment
                        msg += '["'
                        //by this time the msg looks like {"eh_event":"HL7","Segment1":[
                        //loops through all fields inside the current segment we are looking at.
                        //starts at postion 1 instead of 0.  nothing is usually in the 0 index of these messages
                        for(t=1; t< segs[i].fields.length; t++){
                            msg +=  segs[i].fields[t] +' '
                        //msg =msg.slice(0,-1)
                        msg += '"],'
                        //after that loop we now have segment1 filled with all of its fields
                        //msg looks like {"eh_event":"HL7","Segment1":["Field1 Field2 Field3..."],
                    }else msg += segs[i].fields[2] + '",';
                        //log('Else fired')
            //after the segs.fields.length has been exhausted we need to remove the comma that
            // was added to the last element in the array
            msg = msg.slice(0,-1);
            msg += "}"
            /*added closing }
            Finished message as a string looks like:
                   ["Field1 Field2 Field3..."],
                   ["Field1 Field2 Field3..."]
        return msg;
    if(event == "HL7_REQUEST"){
        var segs = HL7.segments;