如何使用mustache呈现JSON模板?

时间:2021-01-30 14:31:07

I'm trying to generate a JSON file with mustache with the following template:

我正在尝试用以下模板生成一个带髭须的JSON文件:

{
    "name": "{{customer_info.first_name}}",
    "email": "{{contact_info.email}}",
    "campaign": {
        "campaignId": "{{contact_info.campaign.campaignId}}"
    },
    "tags": [
        {{#contact_info.tags}} 
        {
            "tagId": "{{tagId}}"
        },
        {{/contact_info.tags}}
    ]
}

As an output example I get:

作为一个输出示例,我得到:

{
    "name": "Antonio",
    "email": "myemail@gmail.com",
    "campaign": {
        "campaignId": "pfft"
    },
    "tags": [
        {
            "tagId": "6prrtAP"
        },
        {
            "tagId": "64rrrE9"
        },
    ]
}

Which unluckily is a BAD FORMATTED JSON, because there is a not wanted "," after the last element in the array.

不幸的是,这是一个糟糕的格式化JSON,因为在数组的最后一个元素后面有一个不需要的“”。

Can any of you help me in solving this issue and remove the comma ?

你们谁能帮我解决这个问题,去掉逗号吗?

Thanks a lot

非常感谢

2 个解决方案

#1


0  

I would do this:

我想这样做:

var md = {};
var tagsCount = 2;
var currTagIndex = 0;
md['show_comma'] = function(){
    currTagIndex++;
    return currTagIndex <= tagsCount;
}

Then in Mustache template:

然后在胡子模板:

{{#show_comma}}
,
{{/show_comma}}

#2


0  

Don't generate JSON from textual templates. You'll constantly face problems like this. Superfluous commas, meta characters in strings (what if customer_info.first_name contains double quotes), failing to properly nest structures etc.

不要从文本模板生成JSON。你会经常遇到这样的问题。多余的逗号,字符串中的元字符(如果customer_info)。first_name包含双引号),未能正确嵌套结构等。

Generate your data as native structures in your programming language, and encode it as JSON using library provided by your programming language.

用编程语言生成本地结构的数据,并使用编程语言提供的库将其编码为JSON。

#1


0  

I would do this:

我想这样做:

var md = {};
var tagsCount = 2;
var currTagIndex = 0;
md['show_comma'] = function(){
    currTagIndex++;
    return currTagIndex <= tagsCount;
}

Then in Mustache template:

然后在胡子模板:

{{#show_comma}}
,
{{/show_comma}}

#2


0  

Don't generate JSON from textual templates. You'll constantly face problems like this. Superfluous commas, meta characters in strings (what if customer_info.first_name contains double quotes), failing to properly nest structures etc.

不要从文本模板生成JSON。你会经常遇到这样的问题。多余的逗号,字符串中的元字符(如果customer_info)。first_name包含双引号),未能正确嵌套结构等。

Generate your data as native structures in your programming language, and encode it as JSON using library provided by your programming language.

用编程语言生成本地结构的数据,并使用编程语言提供的库将其编码为JSON。