Go template to show text if an exact value of a refered attribute

Viewed 21

I'm very new in go templates and honestly I did not understand yet some of the main logic of it, therefore I hope you can turn me into the right direction.

I have a simple JSON for the test (in fact this is the JSON-ized output of a Grafana alerting):

{
  "_15_min_reduced": 1.3122222222222208,
  "_1_min_reduced": 1.7260000000000002,
  "alert": 0,
  "cpu_cores_reduced": 4
}

How can I show a 'message' based on go templates only in case of 1 value of the alert key?

My basic misunderstanding is somewhere here:

{{ . }} shows me the whole map of the JSON node, it's fine.

{{ range . }}
  {{ . }}
{{ end }}

shows me all the values of the keys as a sequence, but not the keys themselves.

{{ .alert }} shows me the value of the 'alert' key (in our sample case is 0).

But...

{{ if eq .alert 1 }}
  There are problems...
{{ end }}

...gives me an 'error'. Seems I can not refer in such was to the defined key, and its value, what is a bit confusing me, as when I directly 'ask' for its value I get the correct result.

Please help me, what is the point where I lost in the go template structure/syntax?!

Lot of thanks for it...

1 Answers

It was a hard run, what I already thought and saw in at firt time, but cound not confirm and verify...

{{ printf "%T" .alert }} shows me that the type of the key is 'float64', what is really incomparable with an 'int' zero. So with a little 'trick'...

{{ if eq .alert 1.0 }}
  There are problems...
{{ end }}

...is already working as in this case 1.0 is a comparable 'float' format.

I tried to convert the value of the .alert to 'int' lot of times/methods but sadly at last unsuccesfully, this is why I slipped into the hole... :(

Really basics, really lame, really my bad, but I hope it could help to anyone in the future...

----- UPDATE #1 ----

Sadly while this final syntax is fine, Grafana still can not accept it so from now I leave it alone :(

Related