-
Notifications
You must be signed in to change notification settings - Fork 135
/
json.go
64 lines (50 loc) · 1.77 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package yttlibrary
import (
"encoding/json"
"fmt"
"github.com/k14s/ytt/pkg/template/core"
"github.com/k14s/ytt/pkg/yamlmeta"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
)
var (
JSONAPI = starlark.StringDict{
"json": &starlarkstruct.Module{
Name: "json",
Members: starlark.StringDict{
"encode": starlark.NewBuiltin("json.encode", core.ErrWrapper(jsonModule{}.Encode)),
"decode": starlark.NewBuiltin("json.decode", core.ErrWrapper(jsonModule{}.Decode)),
},
},
}
)
type jsonModule struct{}
func (b jsonModule) Encode(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if args.Len() != 1 {
return starlark.None, fmt.Errorf("expected exactly one argument")
}
val := core.NewStarlarkValue(args.Index(0)).AsInterface()
val = yamlmeta.NewInterfaceFromAST(val) // convert yaml fragments into Go objects
val = core.NewGoValue(val, false).AsValueWithCheckedMapKeys(true) // JSON only supports string keys
valBs, err := json.Marshal(val)
if err != nil {
return starlark.None, err
}
return starlark.String(string(valBs)), nil
}
func (b jsonModule) Decode(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if args.Len() != 1 {
return starlark.None, fmt.Errorf("expected exactly one argument")
}
valEncoded, err := core.NewStarlarkValue(args.Index(0)).AsString()
if err != nil {
return starlark.None, err
}
var valDecoded interface{}
err = json.Unmarshal([]byte(valEncoded), &valDecoded)
if err != nil {
return starlark.None, err
}
valDecoded = core.NewGoValue(valDecoded, false).AsValueWithCheckedMapKeys(false)
return core.NewGoValue(valDecoded, false).AsStarlarkValue(), nil
}