如何使用小胡子呈现JSON模板

时间:2017-11-02 19:28:38

标签: json mustache

我正在尝试使用以下模板生成带胡子的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}}
    ]
}

作为输出示例,我得到:

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

其中不幸的是一个BAD FORMATTED JSON,因为在数组的最后一个元素之后有一个不想要的“,”。

你们有没有人帮我解决这个问题并删除逗号?

非常感谢

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我会这样做:

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

然后在Mustache模板中:

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

答案 2 :(得分:0)

我一直遇到类似的问题,我发现Handlebars与小胡子非常相似,并且功能更强大。

您可以检查出来并尝试使用此模板解决问题,而无需在当前模型中添加任何内容。

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

答案 3 :(得分:0)

尝试使用SelectTransform npm软件包。它具有类似Mustust的语法,而没有Mustache产生的所有副作用,而且包的大小也不如Handlebars.js

import ST from "stjs";
 
const data = {
  name: 'Jakub',
  friends: [
    {
      name: 'Michal'
    }
  ]
};
 
const template = {
  newName: '{{ name }}',
  friends: {
    '{{ #each friends }}': {
      subName: '{{ name }}'
    }
  }
};
 
console.log(ST.select(data).transformWith(template).root());
 
// Result:
/**
 * {
 *   "newName": "Jakub",
 *   "friends": [
 *     {
 *       "subName": "Michal"
 *     }
 *   ]
 * }
 */
相关问题