Search code examples
jsonhandlebars.jswiremockwiremock-standalone

How to remove the last comma in an each loop in Wiremock


I need to write a stub for a request that would look something like this:

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

The number of todo objects in the request can vary.

My response currently looks like this:

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

Please note that I spaced out the body to make it more readable, in the actual stub, it is all on one line.

So my problem is that I need the comma after my todo object in case there are more than one object passed in the request. This however leaves the last object with a comma as well, so if the above request was sent, this would be the response:

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

This last comma makes .json() method fail in Python application that needs to read the responses from this WireMock stub.

Any thoughts on how to get rid of the last comma? I was thinking maybe having an eq condition around the comma and checking to see if current todo variable is the same as {{jsonPath request.body '$.[-1]'}} but writing it like this:

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

did not work either.

Any suggestions on how to get rid of the last comma would be much appreciated. Thanks :)


Solution

  • Got an answer to this on Google Groups.

    It is possible to use @last within an each loop to detect when you're on the last item e.g:

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