Skip to content

Converting HL7 to JSON with a Template

When the target JSON has a fixed shape and every element maps to a specific HL7 field, a template is the most readable option: hold the JSON body in a System Variable (or the mapping function itself), embed node tags for each substituted value, and run it through qie.evaluateTemplate. QIE resolves each {...} tag against the source HL7 message and returns the rendered JSON as a string that can be handed straight to the outbound message.

The field-by-field alternative (walking each segment in a mapping script and calling setNode per field) is better when the loop counts are dynamic (a variable number of ORCs / OBXs per message). The template approach is better when the shape is fixed and you want the JSON body to be visible as JSON, not assembled by code.

Storing the template in a System Variable

Create a Text-type System Variable named patientTemplate with this value:

{
    "mrn":     "{PID-3.1}",
    "name": {
        "family":  "{PID-5.1}",
        "given":   "{PID-5.2}"
    },
    "birthDate": "{PID-7.1}",
    "gender":    "{PID-8}"
}

In a mapping node's Custom script, evaluate that template and assign the result to the outbound message:

var rendered = qie.evaluateTemplate(qie.getVariable('patientTemplate'));
message.setNode('/', rendered);

qie.getVariable('patientTemplate') reads the raw template text, qie.evaluateTemplate substitutes each node tag against the current source message, and message.setNode('/', ...) replaces the outbound message body wholesale.

Inline template

For a one-off shape that does not need to be reused, keep the template inside the script itself:

var template =
    '{' +
    '  "mrn":     "{PID-3.1}",' +
    '  "name": {' +
    '    "family": "{PID-5.1}",' +
    '    "given":  "{PID-5.2}"' +
    '  }' +
    '}';

message.setNode('/', qie.evaluateTemplate(template));

System-variable storage is preferable when the same template is reused, exported with a package, or edited by someone who does not want to touch the script.

Escaping literal braces

The { and } characters are reserved node-tag delimiters wherever qie.evaluateTemplate runs. A JSON body that legitimately contains a brace not tied to a substitution needs its brace written as an HTML entity. See Escaping Literal Curly Braces for the exact mechanics.