I am new to jsonnet, so I might be missing something.
Issue-1: Custom function only accepts float64, but not integer.
Issue-2: Custom function returning integer throws error but returning float works. (Resolved on latest master. Only affects v0.20.0. )
input.jsonnet
local convertToInt = std.native('convertToInt');
// local replicas = convertToInt(3); -> (Issue-1)This does NOT Accept integer. But float64 works.
local replicas = convertToInt('3');
{
replicas: replicas,
}
main.go
package main
import (
"fmt"
"log"
"strconv"
jsonnet "github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
"gopkg.in/yaml.v3"
)
func main() {
// Create a new Jsonnet VM
vm := jsonnet.MakeVM()
// Custom Golang function embed
jsonToStringFunc := &jsonnet.NativeFunction{
Name: "convertToInt",
Params: ast.Identifiers{"x"},
Func: convertToInt,
}
vm.NativeFunction(jsonToStringFunc)
// Read the Jsonnet file
jsonnetCode, err := vm.EvaluateFile("input.jsonnet")
if err != nil {
log.Fatal(err)
}
// Marshal the output to YAML
var output interface{}
err = yaml.Unmarshal([]byte(jsonnetCode), &output)
if err != nil {
log.Fatal(err)
}
// Print the YAML output
yamlOutput, err := yaml.Marshal(output)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(yamlOutput))
}
func convertToInt(x []interface{}) (interface{}, error) {
log.Printf("%v %T", x, x)
y, ok := x[0].(string)
// y, ok := x[0].(int) // (Issue-1) int does not work, but float64 works, when x is a number.
if !ok {
return nil, fmt.Errorf("Error: Not a string")
}
log.Printf("%v %T", y, y)
num, err := strconv.ParseFloat(y, 10) // works
// num, err := strconv.Atoi(y) // (Issue-2)does not work if returning int
if err != nil {
return nil, err
}
return num, nil
}
I am new to jsonnet, so I might be missing something.
float64
, but not integer.Issue-2: Custom function returning
integer
throws error but returningfloat
works. (Resolved on latest master. Only affectsv0.20.0
. )input.jsonnet
main.go