Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions examples/kubernetes/cel-functions/rg.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ spec:
value: ${schema.spec.fullDNSName.split('.').slice(0, 1).join('.')}
- name: RANDOM_SEEDED_STRING
value: ${random.seededString(10, schema.metadata.uid)}
- name: JSON_UNMARSHAL_EXAMPLE
value: "${json.unmarshal('{\"exampleJSONKey\": \"exampleJSONValue\"}').exampleJSONKey}"
- name: JSON_MARSHAL_EXAMPLE
value: "${json.marshal({\"name\": schema.spec.name})}"
- id: service
template:
apiVersion: v1
Expand Down
2 changes: 2 additions & 0 deletions pkg/cel/ast/inspector.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ type Inspector struct {
// call is better suited than maintaining a hardcoded list.
var knownFunctions = []string{
"random.seededString",
"json.unmarshal",
"json.marshal",
"base64.decode",
"base64.encode",
"lists.range",
Expand Down
1 change: 1 addition & 0 deletions pkg/cel/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ func BaseDeclarations() []cel.EnvOption {
k8scellib.Regex(),
library.Random(),
library.Maps(),
library.JSON(),
}
}

Expand Down
2 changes: 2 additions & 0 deletions pkg/cel/environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ func Test_CELEnvHasFunction(t *testing.T) {
"int", "uint", "double", "bool", "string", "bytes", "timestamp", "duration", "type",
// Custom functions
"random.seededString",
"json.unmarshal",
"json.marshal",
}
for _, fn := range expectedFns {
t.Run(fn, func(t *testing.T) {
Expand Down
143 changes: 143 additions & 0 deletions pkg/cel/library/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Copyright 2025 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package library

import (
"encoding/json"
"math"
"reflect"

"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"

"github.com/kubernetes-sigs/kro/pkg/cel/conversion"
)

// JSON returns a CEL library that provides JSON parsing functions.
//
// Library functions:
//
// json.unmarshal() parses a JSON string and returns the parsed value.
//
// The function takes one argument:
// - jsonString: a string containing JSON
//
// Returns a dynamic type that can be:
// - map for JSON objects
// - list for JSON arrays
// - string, int, double, bool for JSON primitives
// - null for JSON null
//
// Example usage:
//
// json.unmarshal('{"name": "test"}').name
// json.unmarshal('[1,2,3]')[0]
// json.unmarshal(schema.spec.config).enabled
//
// json.marshal() converts a CEL value to a JSON string.
//
// The function takes one argument:
// - value: any CEL value (map, list, string, number, bool, null)
//
// Returns a JSON string representation of the value.
//
// Example usage:
//
// json.marshal({"name": "test", "count": 42})
// json.marshal([1, 2, 3])
// json.marshal(schema.spec.config)
func JSON(options ...JSONOption) cel.EnvOption {
lib := &jsonLibrary{version: math.MaxUint32}
for _, o := range options {
lib = o(lib)
}
return cel.Lib(lib)
}

type jsonLibrary struct {
version uint32
}

// JSONOption is a functional option for configuring the json library.
type JSONOption func(*jsonLibrary) *jsonLibrary

// JSONVersion configures the version of the json library.
func JSONVersion(version uint32) JSONOption {
return func(lib *jsonLibrary) *jsonLibrary {
lib.version = version
return lib
}
}

func (l *jsonLibrary) LibraryName() string {
return "json"
}

func (l *jsonLibrary) CompileOptions() []cel.EnvOption {
return []cel.EnvOption{
cel.Function("json.unmarshal",
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be versioned internally to v1alpha1

Copy link
Copy Markdown
Contributor Author

@NicholasBlaskey NicholasBlaskey Feb 12, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you clarify what you mean for versioned internally here?

I see some other libraries have integer versioning like this but not seeing any use a string version like v1alpha1. The random library also doesn't seem to have any versioning currently.
https://github.com/google/cel-go/blob/v0.27.0/ext/lists.go#L213

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mabye take a look at https://github.com/google/cel-go/blob/v0.27.0/ext/lists.go#L175-L189 or https://github.com/google/cel-go/blob/v0.27.0/ext/sets.go#L88-L97. Its basically about introducing a version so we can control it later. i dont really mind if its v1alpha1 or an integer tbh.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added support for setting a version

currently the version integer is unused but can be referenced for future updates to the library

cel.Overload("json.unmarshal_string",
[]*cel.Type{cel.StringType},
cel.DynType,
cel.UnaryBinding(unmarshalJSON),
),
),
cel.Function("json.marshal",
cel.Overload("json.marshal_dyn",
[]*cel.Type{cel.DynType},
cel.StringType,
cel.UnaryBinding(marshalJSON),
),
),
}
}

func (l *jsonLibrary) ProgramOptions() []cel.ProgramOption {
return nil
}

func unmarshalJSON(jsonString ref.Val) ref.Val {
native, err := jsonString.ConvertToNative(reflect.TypeOf(""))
if err != nil {
return types.NewErr("json.unmarshal argument must be a string")
}

str, ok := native.(string)
if !ok {
return types.NewErr("json.unmarshal argument must be a string")
}

var result interface{}
if err := json.Unmarshal([]byte(str), &result); err != nil {
return types.NewErr("json.unmarshal failed to parse JSON: %s", err.Error())
}

return types.DefaultTypeAdapter.NativeToValue(result)
}

func marshalJSON(value ref.Val) ref.Val {
native, err := conversion.GoNativeType(value)
if err != nil {
return types.NewErr("json.marshal failed to convert value: %s", err.Error())
}

jsonBytes, err := json.Marshal(native)
if err != nil {
return types.NewErr("json.marshal failed to encode value: %s", err.Error())
}

return types.String(string(jsonBytes))
}
Loading