Creating JSON with the template node

We are having some difficulties creating a JSON document with an Template node using mustache. There seems to be no way to create the contact array and producing valid JSON output:

   {
     "status": "valid",
     "contact": [
       "mailto:cert-admin@example.org",
       "mailto:admin@example.org"
     ],
     "termsOfServiceAgreed": true,
     "orders": "https://example.com/acme/orders/rzGoeA"
   }

Our current solution looks like this:

{
    "status": "{{ account.status }}",
    "contact": [
    {{#account.contacts}}
        "{{ email }}",
    {{/account.contacts}}
    ],
    "orders": "https://{{ domain }}/acme/{{ caname }}/orders"
}

But this creates an additional , at the end of the last array entry. It there any trick to using mustache for creating valid JSON arrays?

Is there any way to add another templating engine like handlebars?

I don't think so. Mustache is made for text and although json strings are text, it does not have this kind of logic built in.

This is not hard to do with a function node instead.

Where do you see the extra comma?

Would this solution work out for you? Probably not without modifying the object with jsonata first, so rendering it with jsonata might work out better instead :thinking:

That wil loop through account.contacts and for every item in it, add the email property of each object in a string, ending with a comma. That comma in the last element of that loop is the issue as that wouldn’t be valid json

@augjoh you have a discrepancy in the data and the template. In the data you have contact while in the template you have the plural contacts

Not the case. Top is expected output. Bottom is the used template. No input data present :slight_smile:

Ahhh right, then it would be nice to see what the actual data going into the template is

I've replaced the standard template node with node-red-contrib-handlebars. The following template handles the comma issue.

{
    "status": "{{ account.status }}",
    "orders": "https://{{ domain }}/acme/{{ caname }}/orders",
    "contact": [
        {{#each account.contacts }}
            "{{ . }}"{{#unless @last}},{{/unless}}
        {{/each}}
    ]
}

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.