-
Notifications
You must be signed in to change notification settings - Fork 3.6k
[pkg/ottl] Add ParseJSONIntoMap function #16340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| # One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' | ||
| change_type: enhancement | ||
|
|
||
| # The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver) | ||
| component: pkg/ottl | ||
|
|
||
| # A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). | ||
| note: Add new `ParseJSONIntoMap` function to convert json strings into attributes. | ||
|
|
||
| # One or more tracking issues related to the change | ||
| issues: [16340] | ||
|
|
||
| # (Optional) One or more lines of additional information to render under the primary note. | ||
| # These lines will be padded with 2 spaces and then inserted directly into the document. | ||
| # Use pipe (|) for multiline entries. | ||
| subtext: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| // Copyright The OpenTelemetry 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 ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs" | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| jsoniter "github.com/json-iterator/go" | ||
| "go.opentelemetry.io/collector/pdata/pcommon" | ||
|
|
||
| "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
| ) | ||
|
|
||
| func ParseJSONIntoMap[K any](target ottl.GetSetter[K], value ottl.Getter[K]) (ottl.ExprFunc[K], error) { | ||
| return func(ctx context.Context, tCtx K) (interface{}, error) { | ||
| targetVal, err := target.Get(ctx, tCtx) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if attrs, ok := targetVal.(pcommon.Map); ok { | ||
| val, err := value.Get(ctx, tCtx) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if valStr, ok := val.(string); ok { | ||
| var parsedValue map[string]interface{} | ||
| err = jsoniter.UnmarshalFromString(valStr, &parsedValue) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| for k, v := range parsedValue { | ||
| attrVal := pcommon.NewValueEmpty() | ||
| err = setValue(attrVal, v) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| attrVal.CopyTo(attrs.PutEmpty(k)) | ||
| } | ||
| } | ||
| } | ||
| return nil, nil | ||
| }, nil | ||
| } | ||
|
|
||
| func setValue(value pcommon.Value, val interface{}) error { | ||
| switch v := val.(type) { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we add a default case to guard against unknown types and return an error? |
||
| case string: | ||
| value.SetStr(v) | ||
| case bool: | ||
| value.SetBool(v) | ||
| case float64: | ||
| value.SetDouble(v) | ||
| case nil: | ||
| case []interface{}: | ||
| emptySlice := value.SetEmptySlice() | ||
| err := setSlice(emptySlice, v) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| case map[string]interface{}: | ||
| mapStr, err := jsoniter.MarshalToString(val) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| value.SetStr(mapStr) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func setSlice(slice pcommon.Slice, value []interface{}) error { | ||
| for _, item := range value { | ||
| emptyValue := slice.AppendEmpty() | ||
| err := setValue(emptyValue, item) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| // Copyright The OpenTelemetry 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 ottlfuncs | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "go.opentelemetry.io/collector/pdata/pcommon" | ||
|
|
||
| "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
| ) | ||
|
|
||
| func Test_ParseJSONIntoMap(t *testing.T) { | ||
| input := pcommon.NewMap() | ||
| input.PutStr("existing", "attr") | ||
|
|
||
| target := &ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return tCtx, nil | ||
| }, | ||
| Setter: func(ctx context.Context, tCtx pcommon.Map, val interface{}) error { | ||
| val.(pcommon.Map).CopyTo(tCtx) | ||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| target ottl.GetSetter[pcommon.Map] | ||
| value ottl.Getter[pcommon.Map] | ||
| want func(pcommon.Map) | ||
| }{ | ||
| { | ||
| name: "handle string", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":"string value"}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutStr("test", "string value") | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle bool", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":true}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutBool("test", true) | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle int", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":1}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutDouble("test", 1) | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle float", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":1.1}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutDouble("test", 1.1) | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle nil", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":null}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutEmpty("test") | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle array", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":["string","value"]}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| emptySlice := expectedMap.PutEmptySlice("test") | ||
| emptySlice.AppendEmpty().SetStr("string") | ||
| emptySlice.AppendEmpty().SetStr("value") | ||
| }, | ||
| }, | ||
| { | ||
| name: "handle nested object", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test":{"nested":"true"}}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutStr("test", `{"nested":"true"}`) | ||
|
djaglowski marked this conversation as resolved.
|
||
| }, | ||
| }, | ||
| { | ||
| name: "updates existing", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"existing":"pass"}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutStr("existing", "pass") | ||
| }, | ||
| }, | ||
| { | ||
| name: "complex", | ||
| target: target, | ||
| value: ottl.StandardGetSetter[pcommon.Map]{ | ||
| Getter: func(ctx context.Context, tCtx pcommon.Map) (interface{}, error) { | ||
| return `{"test1":{"nested":"true"},"test2":"string","test3":1,"test4":1.1,"test5":["string", 1, [2, 3],{"nested":true}],"test6":null}`, nil | ||
| }, | ||
| }, | ||
| want: func(expectedMap pcommon.Map) { | ||
| expectedMap.PutStr("test1", `{"nested":"true"}`) | ||
| expectedMap.PutStr("test2", "string") | ||
| expectedMap.PutDouble("test3", 1) | ||
| expectedMap.PutDouble("test4", 1.1) | ||
| slice := expectedMap.PutEmptySlice("test5") | ||
| slice.AppendEmpty().SetStr("string") | ||
| slice.AppendEmpty().SetDouble(1) | ||
| nestedSlice := slice.AppendEmpty().SetEmptySlice() | ||
| nestedSlice.AppendEmpty().SetDouble(2) | ||
| nestedSlice.AppendEmpty().SetDouble(3) | ||
| slice.AppendEmpty().SetStr(`{"nested":true}`) | ||
| expectedMap.PutEmpty("test6") | ||
| }, | ||
| }, | ||
| } | ||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| scenarioMap := pcommon.NewMap() | ||
| input.CopyTo(scenarioMap) | ||
|
|
||
| exprFunc, err := ParseJSONIntoMap(tt.target, tt.value) | ||
| assert.NoError(t, err) | ||
|
|
||
| result, err := exprFunc(context.Background(), scenarioMap) | ||
| assert.NoError(t, err) | ||
| assert.Nil(t, result) | ||
|
|
||
| expected := pcommon.NewMap() | ||
| input.CopyTo(expected) | ||
| tt.want(expected) | ||
|
|
||
| assert.Equal(t, expected.Len(), scenarioMap.Len()) | ||
| expected.Range(func(k string, v pcommon.Value) bool { | ||
| ev, _ := expected.Get(k) | ||
| av, _ := scenarioMap.Get(k) | ||
| assert.Equal(t, ev, av) | ||
| return true | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just an idea: I think we will end with multiple parseIntoMap that accepts multiple formats, JSON/YAML/etc. Do you think it is worth accepting the format as argument instead?