How to inject filed in JSON object using Handlebars in Wiremock response templating

502 Views Asked by At

Wiremock docker image: wiremock/wiremock:2.35.0.
I am using docker image of Wiremock server, and I need to create a mock for custom response based on the request's body.
Futhermore, I need to add a custom field in the response.
Handlebars doesn't have a built-in function/helper for this.
Although it allows to iterate through the original JSON object, it does not know the type of each field.

So basically I want to transform this:

{
  "number": 123,
  "text": "test",
  "array": [
      1,
      2,
      3
  ],
  "nested object": [
      {
          "a": 1,
          "text": "test",
          "array": [
              {
                  "a": 1
              }
          ]
      }
  ]
}

into this:

{
  "my field": 123,
  "number": 123,
  "text": "test",
  "array": [
      1,
      2,
      3
  ],
  "nested object": [
      {
          "a": 1,
          "text": "test",
          "array": [
              {
                  "a": 1
              }
          ]
      }
  ]
}

I tried this tempate, but it doesn't work:

{\"my field\": 123, {{#each (jsonPath request.body '$')}} \"{{@key}}\": \"{{this}}\", {{/each}}}

It doesn't allow to

1

There are 1 best solutions below

0
On BEST ANSWER

Actually, I found the solution myself, just wanted to document the knowledge here.
All you need to do is to use substring string helper.
The template for body will look like this:

{\"my field\": 123, {{{substring (jsonPath request.body '$') 1}}}

Here we are removing the first curly brace and placing our custom field instead.