5

I have a string that contains a number in a Jsonnet variable. How do I convert it to an integer?

sbarzowski
  • 2,707
  • 1
  • 20
  • 25
kgraney
  • 1,975
  • 16
  • 20

2 Answers2

6

Jsonnet's standard library provides a: std.parseInt(str) function that can parse a signed decimal integer from a given input string. For example:

std.parseInt("123") // yields 123
std.parseInt("-456") // yields -456

Reference: http://jsonnet.org/docs/stdlib.html

mohitsoni
  • 3,091
  • 3
  • 19
  • 10
0

The Jsonnet standard library is fairly thin, but here is an example of a Jsonnet function that does this conversion.

{
    string_to_int(s)::
        local char_to_int(c) = std.codepoint(c) - std.codepoint("0");
        local digits = std.map(char_to_int, std.stringChars(s));
        std.foldr(function(x,y) x+y,
                  std.makeArray(std.length(digits),
                                function(x) digits[std.length(digits)-x-1]*std.pow(10, x)),
                  0),
}
kgraney
  • 1,975
  • 16
  • 20