4 "github.com/zclconf/go-cty/cty"
5 "github.com/zclconf/go-cty/cty/function"
6 "github.com/zclconf/go-cty/cty/json"
9 var JSONEncodeFunc = function.New(&function.Spec{
10 Params: []function.Parameter{
13 Type: cty.DynamicPseudoType,
14 AllowDynamicType: true,
17 Type: function.StaticReturnType(cty.String),
18 Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
20 if !val.IsWhollyKnown() {
21 // We can't serialize unknowns, so if the value is unknown or
22 // contains any _nested_ unknowns then our result must be
24 return cty.UnknownVal(retType), nil
27 buf, err := json.Marshal(val, val.Type())
29 return cty.NilVal, err
32 return cty.StringVal(string(buf)), nil
36 var JSONDecodeFunc = function.New(&function.Spec{
37 Params: []function.Parameter{
43 Type: func(args []cty.Value) (cty.Type, error) {
46 return cty.DynamicPseudoType, nil
49 buf := []byte(str.AsString())
50 return json.ImpliedType(buf)
52 Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
53 buf := []byte(args[0].AsString())
54 return json.Unmarshal(buf, retType)
58 // JSONEncode returns a JSON serialization of the given value.
59 func JSONEncode(val cty.Value) (cty.Value, error) {
60 return JSONEncodeFunc.Call([]cty.Value{val})
63 // JSONDecode parses the given JSON string and, if it is valid, returns the
64 // value it represents.
66 // Note that applying JSONDecode to the result of JSONEncode may not produce
67 // an identically-typed result, since JSON encoding is lossy for cty Types.
68 // The resulting value will consist only of primitive types, object types, and
70 func JSONDecode(str cty.Value) (cty.Value, error) {
71 return JSONDecodeFunc.Call([]cty.Value{str})