aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go')
-rw-r--r--vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go72
1 files changed, 72 insertions, 0 deletions
diff --git a/vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go b/vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go
new file mode 100644
index 0000000..07901c6
--- /dev/null
+++ b/vendor/github.com/zclconf/go-cty/cty/function/stdlib/json.go
@@ -0,0 +1,72 @@
1package stdlib
2
3import (
4 "github.com/zclconf/go-cty/cty"
5 "github.com/zclconf/go-cty/cty/function"
6 "github.com/zclconf/go-cty/cty/json"
7)
8
9var JSONEncodeFunc = function.New(&function.Spec{
10 Params: []function.Parameter{
11 {
12 Name: "val",
13 Type: cty.DynamicPseudoType,
14 AllowDynamicType: true,
15 },
16 },
17 Type: function.StaticReturnType(cty.String),
18 Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
19 val := args[0]
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
23 // unknown.
24 return cty.UnknownVal(retType), nil
25 }
26
27 buf, err := json.Marshal(val, val.Type())
28 if err != nil {
29 return cty.NilVal, err
30 }
31
32 return cty.StringVal(string(buf)), nil
33 },
34})
35
36var JSONDecodeFunc = function.New(&function.Spec{
37 Params: []function.Parameter{
38 {
39 Name: "str",
40 Type: cty.String,
41 },
42 },
43 Type: func(args []cty.Value) (cty.Type, error) {
44 str := args[0]
45 if !str.IsKnown() {
46 return cty.DynamicPseudoType, nil
47 }
48
49 buf := []byte(str.AsString())
50 return json.ImpliedType(buf)
51 },
52 Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
53 buf := []byte(args[0].AsString())
54 return json.Unmarshal(buf, retType)
55 },
56})
57
58// JSONEncode returns a JSON serialization of the given value.
59func JSONEncode(val cty.Value) (cty.Value, error) {
60 return JSONEncodeFunc.Call([]cty.Value{val})
61}
62
63// JSONDecode parses the given JSON string and, if it is valid, returns the
64// value it represents.
65//
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
69// tuple types.
70func JSONDecode(str cty.Value) (cty.Value, error) {
71 return JSONDecodeFunc.Call([]cty.Value{str})
72}