• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
2
3package common
4
5import (
6	"encoding/json"
7	"fmt"
8	"strings"
9)
10
11type Annotator struct {
12	Annotator string
13	// including AnnotatorType: one of "Person", "Organization" or "Tool"
14	AnnotatorType string
15}
16
17// UnmarshalJSON takes an annotator in the typical one-line format and parses it into an Annotator struct.
18// This function is also used when unmarshalling YAML
19func (a *Annotator) UnmarshalJSON(data []byte) error {
20	// annotator will simply be a string
21	annotatorStr := string(data)
22	annotatorStr = strings.Trim(annotatorStr, "\"")
23
24	annotatorFields := strings.SplitN(annotatorStr, ": ", 2)
25
26	if len(annotatorFields) != 2 {
27		return fmt.Errorf("failed to parse Annotator '%s'", annotatorStr)
28	}
29
30	a.AnnotatorType = annotatorFields[0]
31	a.Annotator = annotatorFields[1]
32
33	return nil
34}
35
36// MarshalJSON converts the receiver into a slice of bytes representing an Annotator in string form.
37// This function is also used when marshalling to YAML
38func (a Annotator) MarshalJSON() ([]byte, error) {
39	if a.Annotator != "" {
40		return json.Marshal(fmt.Sprintf("%s: %s", a.AnnotatorType, a.Annotator))
41	}
42
43	return []byte{}, nil
44}
45