如何删除 Wiremock 中每个循环中的最后一个逗号

问题描述 投票:0回答:2

我需要为请求编写一个存根,如下所示:

[
    { "todo_id": 1 },
    { "todo_id": 2 }
]

请求中的待办事项对象的数量可能会有所不同。

我的回复目前如下所示:

"response": {
    "status": 200,
    "body": "[ {{#each (jsonPath request.body '$') as |todo|}}
                   { \"todo_id\": {{todo.todo_id}} },
               {{/each}}
             ]"
}

请注意,我将正文隔开以使其更具可读性,在实际的存根中,它全部在一行上。

所以我的问题是,我需要在 todo 对象后面加上逗号,以防请求中传递多个对象。然而,这也会给最后一个对象留下一个逗号,所以如果发送了上述请求,这将是响应:

[
    { "todo_id": 1 },
    { "todo_id": 2 },
]

最后一个逗号使得

.json()
方法在需要从此 WireMock 存根读取响应的 Python 应用程序中失败。

关于如何去掉最后一个逗号有什么想法吗?我想也许在逗号周围有一个

eq
条件,并检查当前
todo
变量是否与
{{jsonPath request.body '$.[-1]'}}
相同,但这样写:

{{#eq todo {{jsonPath request.body '$.[-1]'}} }}

也没有用。

任何有关如何去掉最后一个逗号的建议将不胜感激。谢谢:)

json handlebars.js wiremock wiremock-standalone
2个回答
3
投票

在 Google 网上论坛上找到了这个问题的答案。

可以在每个循环中使用

@last
来检测您何时位于最后一项,例如:

{{#each (jsonPath request.body '$.things') as |thing|}}
  {{#if @last}}
    { "thing": {{{thing}}} }
  {{else}}
    { "thing": {{{thing}}} },
  {{/if}}
{{/each}}

0
投票

您可能还会发现

{{#unless}}
标签很有用,因为它充当事实上的“not if”,如下所示:

{{#each (jsonPath request.body '$.things') as |thing|}}
  { "thing": {{{thing}}} }{{#unless @last}},{{/unless}}
{{/each}}
© www.soinside.com 2019 - 2024. All rights reserved.