Response Body Transform unable to write correct template

The api responds with this response [
{
“name”: “kubernetes”,
“id”: 1
},
{
“name”: “docker”,
“id”: 2
},
{
“name”: “tyk”,
“id”: 3
}
]

I am trying to write a response body transform that would only display first two data values.
For the same i am using this template

[
{
“name”: “{{0.name}}”,
“id”: “{{0.id}}”
},
{
“name”: “{{1.name}}”,
“id”: “{{1.id}}”
}
]
which throws an error. What could be possible template definition for this use case that works.

Hi

It’s a little more in depth than what you are trying there.

To get that output you can use this template:

[{{range $i, $a := .}}{{ if ne $a.name "tyk"}}{{ if $i}},{{ end }}{
    "name" : "{{index $a.name}}",
    "id" : {{index $a.id}}
}
{{end}}
{{end}}]

There are a few simple Go template tricks here:

  1. We need a range to access the items iteratively in our slice
  2. The {{ if $i}},{{ end }} is a trick where we are emitting the comma seperator for our list first but not for the first item in our slice (this only prints when non-zero)
  3. There may be a better way to do this but ive just added an equivalency check to skip a certain matching property in our slice

Hope this helps you out!

Josh

1 Like