Sesam DTL-痛苦地创建复杂的json输出

时间:2018-09-11 12:41:07

标签: sesam

当前,越来越多的管道在json中发送数据。但是创建一个复杂的json很麻烦,因为我们必须使用很多嵌套的“ dict”和“ list”。很难读取此类dtl并对输出进行映像。有没有更好的方法通过dtl创建json?

我认为,最好的解决方案可能是“使用一些模板”,然后将jinja2之类的变量替换为xml和html,例如:

  • [“ add”,“ output_template”,“ {'id”:$ V(_id),'name': $ V(namespace:name),'address':{'street':$ V(namespace:street), 邮政编码:$ V(namespace:zipcode)}}“]。
  • [“ json_render”,_ T.output_template,_S]。

所有$ V变量将被“ _S”或“ _T”中的键替换。

1 个答案:

答案 0 :(得分:2)

您可以像这样用DTL构建自己的模板引擎:

{
  "_id": "template",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": {
      "_id": "foo",
      "namespace:name": "Baard",
      "namespace:street": "Rødhettes vei 5",
      "namespace:zipcode": "1482"
    }
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["add", "output_template", {
          "name": "$V(namespace:name)",
          "address": {
            "street": "$V(namespace:street)",
            "zipcode": "$V(namespace:zipcode)"
          },
          "id": "$V(_id)"
        }],
        ["add", "output",
          ["apply", "template-engine", "_T.output_template"]
        ]
      ],
      "template-engine": [
        ["merge",
          ["map-dict", "_.",
            ["if",
              ["matches", "$V(*)", "_."],
              ["path",
                ["lstrip", "$V(",
                  ["rstrip", ")", "_."]
                ], "_R._S"],
              ["if",
                ["is-dict", "_."],
                ["apply", "template-engine", "_."]
              ]
            ], "_S."]
        ]
      ]
    }
  }
}

这将为您提供以下输出:

[
  {
    "_id": "foo",
    "output": {
      "address": {
        "street": "Rødhettes vei 5",
        "zipcode": "1482"
      },
      "id": "foo",
      "name": "Baard"
    },
    "output_template": {
      "address": {
        "street": "$V(namespace:street)",
        "zipcode": "$V(namespace:zipcode)"
      },
      "id": "$V(_id)",
      "name": "$V(namespace:name)"
    }
  }
]