Jsonnet: Is there any way to force numbers like 100.0 to output as float?

Created on 27 Jul 2019  路  3Comments  路  Source: google/jsonnet

(or just decimal)

I have a program that expects floats always in some YAML keys. Is there a way to make that program happy without altering its function?

use case: https://github.com/RavuAlHemio/prometheus_aci_exporter/blob/master/examples/aci.yml#L241

failure mode:

$ cat /tmp/z.jsonnet
{
 canHasFloat: 100000000000.0,
}

$ jsonnet /tmp/z.jsonnet
{
 "canHasFloat": 100000000000
}

Most helpful comment

You'd need custom YAML output here that is specific for prometheus. Jsonnet assumes that YAML consumers will not distinguish between !!float 0 and !!int 0 because they are indistinguishable in JSON. I've never seen a YAML consumer that does this before, generally best practice is to only use YAML features that will round-trip through JSON, because otherwise data interchange is very hard.

All 3 comments

First of all, technically if the reader treats them differently (in a way that's problematic) it's a problem on their side. I mean I'm pretty sure they are equivalent from JSON spec perspective. So I would consider fixing it on the side of Jsonnet code a hack.

That said, of course you can make Jsonnet output any string of characters you want. With jsonnet -S the result of Jsonnet evaluation is treated as a string and printed to stdout without any escaping. And then you can write a custom manifestation function which can produce any output you like, including special treatment of some fields or integers in general. You can take a look at a manifester implementation here for inspiration: https://github.com/google/jsonnet/blob/master/stdlib/std.jsonnet#L890

If you go this path, your new program could look something like:

local myManifestation(x) = ...;
local result = <your_old_program>;
myManifestation(result)

and you would run it with -S option.

I'll be happy to help if you have any further questions.

You'd need custom YAML output here that is specific for prometheus. Jsonnet assumes that YAML consumers will not distinguish between !!float 0 and !!int 0 because they are indistinguishable in JSON. I've never seen a YAML consumer that does this before, generally best practice is to only use YAML features that will round-trip through JSON, because otherwise data interchange is very hard.

Thanks @sbarzowski and @sparkprime. I'll try to solve it on the other side as mentioned. If nothing else, I can try the manifestation trick @sbarzowski mentioned. Cheers!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

augi picture augi  路  7Comments

lukasheinrich picture lukasheinrich  路  7Comments

mbrukman picture mbrukman  路  4Comments

ant31 picture ant31  路  6Comments

sbarzowski picture sbarzowski  路  7Comments