From 9b68dee4169531edbcb8d947aaafcfb24f425a86 Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Fri, 15 Dec 2023 09:29:48 +0545 Subject: [PATCH] feat: add .JSON() & .JSONArray() methods to string --- funcs/cel_exports.go | 2 ++ funcs/data_gen.go | 36 +++++++++++++++++++++++++++++++++--- tests/cel_test.go | 5 +++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/funcs/cel_exports.go b/funcs/cel_exports.go index c63a71cd2..af22a45e3 100644 --- a/funcs/cel_exports.go +++ b/funcs/cel_exports.go @@ -61,8 +61,10 @@ var CelEnvOption = []cel.EnvOption{ // JSON dataJSONGen, + dataJSONMemberGen, dataToJSONGen2, dataJSONArrayGen, + dataJSONArrayMemberGen, dataToJSONGen, dataToJSONPrettyGen, diff --git a/funcs/data_gen.go b/funcs/data_gen.go index 07d97bdff..cdd810789 100644 --- a/funcs/data_gen.go +++ b/funcs/data_gen.go @@ -33,23 +33,53 @@ var dataJSONGen = cel.Function("JSON", ), ) +var dataJSONMemberGen = cel.Function("JSON", + cel.MemberOverload(".string.JSON()", + []*cel.Type{ + cel.StringType, + }, + cel.DynType, + cel.UnaryBinding(func(arg ref.Val) ref.Val { + var x DataFuncs + result, err := x.JSON(arg) + if err != nil { + return types.WrapErr(err) + } + return types.DefaultTypeAdapter.NativeToValue(result) + }), + ), +) + var dataJSONArrayGen = cel.Function("JSONArray", cel.Overload("JSONArray_interface{}", - []*cel.Type{ cel.DynType, }, cel.DynType, cel.FunctionBinding(func(args ...ref.Val) ref.Val { - var x DataFuncs - result, err := x.JSONArray(args[0]) if err != nil { return types.WrapErr(err) } return types.DefaultTypeAdapter.NativeToValue(result) + }), + ), +) +var dataJSONArrayMemberGen = cel.Function("JSONArray", + cel.MemberOverload(".string.JSONArray()", + []*cel.Type{ + cel.StringType, + }, + cel.DynType, + cel.UnaryBinding(func(arg ref.Val) ref.Val { + var x DataFuncs + result, err := x.JSONArray(arg) + if err != nil { + return types.WrapErr(err) + } + return types.DefaultTypeAdapter.NativeToValue(result) }), ), ) diff --git a/tests/cel_test.go b/tests/cel_test.go index 0eef44d19..b344c2821 100644 --- a/tests/cel_test.go +++ b/tests/cel_test.go @@ -161,6 +161,11 @@ func TestCelJSON(t *testing.T) { {nil, `[{'name': 'John'}].toJSON()`, `[{"name":"John"}]`}, {nil, `dyn({'name': 'John'}).toJSON()`, `{"name":"John"}`}, {nil, `{'name': 'John'}.toJSON()`, `{"name":"John"}`}, + {nil, `toJSON({'name': 'John'})`, `{"name":"John"}`}, + {nil, `1.toJSON()`, `1`}, + {nil, `'{"name": "John"}'.JSON().name`, `John`}, + {nil, `'{"name": "Alice", "age": 30}'.JSON().name`, `Alice`}, + {nil, `'[1, 2, 3, 4, 5]'.JSONArray()[0]`, `1`}, {map[string]interface{}{"i": person}, "jq('.Address.city_name', i)", "Kathmandu"}, {map[string]interface{}{"i": person}, "toJSONPretty('\t', i)", "{\n\t\"Address\": {\n\t\t\"city_name\": \"Kathmandu\"\n\t},\n\t\"name\": \"Aditya\"\n}"}, {map[string]interface{}{"i": person}, "toJSONPretty('\t', [\"Alice\", 30])", "[\n\t\"Alice\",\n\t30\n]"},