Skip to content

Commit

Permalink
[chore][pkg/stanza] Cleanup json parser operator files (open-telemetr…
Browse files Browse the repository at this point in the history
  • Loading branch information
djaglowski committed Apr 4, 2024
1 parent 18eee5c commit 5385fb0
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@
package json // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/parser/json"

import (
"context"
"fmt"

jsoniter "github.com/json-iterator/go"
"go.uber.org/zap"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
)
Expand Down Expand Up @@ -50,29 +46,3 @@ func (c Config) Build(logger *zap.SugaredLogger) (operator.Operator, error) {
json: jsoniter.ConfigFastest,
}, nil
}

// Parser is an operator that parses JSON.
type Parser struct {
helper.ParserOperator
json jsoniter.API
}

// Process will parse an entry for JSON.
func (j *Parser) Process(ctx context.Context, entry *entry.Entry) error {
return j.ParserOperator.ProcessWith(ctx, entry, j.parse)
}

// parse will parse a value as JSON.
func (j *Parser) parse(value any) (any, error) {
var parsedValue map[string]any
switch m := value.(type) {
case string:
err := j.json.UnmarshalFromString(m, &parsedValue)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("type %T cannot be parsed as JSON", value)
}
return parsedValue, nil
}
40 changes: 40 additions & 0 deletions pkg/stanza/operator/parser/json/parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package json // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/parser/json"

import (
"context"
"fmt"

jsoniter "github.com/json-iterator/go"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
)

// Parser is an operator that parses JSON.
type Parser struct {
helper.ParserOperator
json jsoniter.API
}

// Process will parse an entry for JSON.
func (p *Parser) Process(ctx context.Context, entry *entry.Entry) error {
return p.ParserOperator.ProcessWith(ctx, entry, p.parse)
}

// parse will parse a value as JSON.
func (p *Parser) parse(value any) (any, error) {
var parsedValue map[string]any
switch m := value.(type) {
case string:
err := p.json.UnmarshalFromString(m, &parsedValue)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("type %T cannot be parsed as JSON", value)
}
return parsedValue, nil
}

0 comments on commit 5385fb0

Please sign in to comment.