forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
40 lines (33 loc) · 1.05 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
}