Skip to content

Commit

Permalink
fix: handle string pointer in fromJSON builtin
Browse files Browse the repository at this point in the history
Support *string input in fromJSON builtin function by
dereferencing pointer before JSON unmarshaling.

Added tests covering both direct string and pointer string
use cases, including toJSON, which already supports this.

Signed-off-by: Ville Vesilehto <[email protected]>
  • Loading branch information
thevilledev committed Jan 25, 2025
1 parent 192ab82 commit 86798a6
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
6 changes: 5 additions & 1 deletion builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,11 @@ var Builtins = []*Function{
Name: "fromJSON",
Func: func(args ...any) (any, error) {
var v any
err := json.Unmarshal([]byte(args[0].(string)), &v)
jsonStr := args[0]
if strPtr, ok := jsonStr.(*string); ok {
jsonStr = *strPtr
}
err := json.Unmarshal([]byte(jsonStr.(string)), &v)
if err != nil {
return nil, err
}
Expand Down
52 changes: 52 additions & 0 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -638,3 +638,55 @@ func Test_int_unwraps_underlying_value(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, true, out)
}

func TestBuiltin_json(t *testing.T) {
t.Run("fromJSON/string", func(t *testing.T) {
env := map[string]any{
"json": `{"foo": "bar"}`,
}
program, err := expr.Compile(`fromJSON(json)`, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
assert.Equal(t, map[string]any{"foo": "bar"}, out)
})

t.Run("fromJSON/string pointer", func(t *testing.T) {
jsonString := `{"foo": "bar"}`
env := map[string]any{
"json": &jsonString,
}
program, err := expr.Compile(`fromJSON(json)`, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
assert.Equal(t, map[string]any{"foo": "bar"}, out)
})

t.Run("toJSON/object", func(t *testing.T) {
env := map[string]any{
"obj": map[string]any{"foo": "bar"},
}
program, err := expr.Compile(`toJSON(obj)`, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
assert.Equal(t, "{\n \"foo\": \"bar\"\n}", out)
})

t.Run("toJSON/object pointer", func(t *testing.T) {
obj := map[string]any{"foo": "bar"}
env := map[string]any{
"obj": &obj,
}
program, err := expr.Compile(`toJSON(obj)`, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
assert.Equal(t, "{\n \"foo\": \"bar\"\n}", out)
})
}

0 comments on commit 86798a6

Please sign in to comment.