yq/pkg/yqlib/encoder_json.go

66 lines
1.3 KiB
Go
Raw Permalink Normal View History

//go:build !yq_nojson
package yqlib
import (
2022-05-22 11:19:59 +00:00
"bytes"
"io"
2022-07-27 02:26:22 +00:00
"github.com/goccy/go-json"
)
type jsonEncoder struct {
2024-02-24 04:48:59 +00:00
prefs JsonPreferences
indentString string
}
2024-02-24 04:48:59 +00:00
func NewJSONEncoder(prefs JsonPreferences) Encoder {
var indentString = ""
2024-02-24 04:48:59 +00:00
for index := 0; index < prefs.Indent; index++ {
indentString = indentString + " "
}
2024-02-24 04:48:59 +00:00
return &jsonEncoder{prefs, indentString}
}
func (je *jsonEncoder) CanHandleAliases() bool {
return false
}
2024-01-11 02:17:34 +00:00
func (je *jsonEncoder) PrintDocumentSeparator(_ io.Writer) error {
return nil
}
2024-01-11 02:17:34 +00:00
func (je *jsonEncoder) PrintLeadingContent(_ io.Writer, _ string) error {
return nil
}
func (je *jsonEncoder) Encode(writer io.Writer, node *CandidateNode) error {
log.Debugf("I need to encode %v", NodeToString(node))
log.Debugf("kids %v", len(node.Content))
2022-05-22 11:19:59 +00:00
2024-02-24 04:48:59 +00:00
if node.Kind == ScalarNode && je.prefs.UnwrapScalar {
return writeString(writer, node.Value+"\n")
}
2022-05-22 11:19:59 +00:00
destination := writer
tempBuffer := bytes.NewBuffer(nil)
2024-02-24 04:48:59 +00:00
if je.prefs.ColorsEnabled {
2022-05-22 11:19:59 +00:00
destination = tempBuffer
}
var encoder = json.NewEncoder(destination)
encoder.SetEscapeHTML(false) // do not escape html chars e.g. &, <, >
encoder.SetIndent("", je.indentString)
err := encoder.Encode(node)
2022-05-22 11:19:59 +00:00
if err != nil {
return err
}
2024-02-24 04:48:59 +00:00
if je.prefs.ColorsEnabled {
2022-05-22 11:19:59 +00:00
return colorizeAndPrint(tempBuffer.Bytes(), writer)
}
return nil
}