2023-03-01 02:19:06 +00:00
|
|
|
//go:build !yq_nojson
|
|
|
|
|
2022-01-15 00:57:59 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
2022-05-22 11:19:59 +00:00
|
|
|
"bytes"
|
2022-01-15 00:57:59 +00:00
|
|
|
"io"
|
|
|
|
|
2022-07-27 02:26:22 +00:00
|
|
|
"github.com/goccy/go-json"
|
2022-01-15 00:57:59 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type jsonEncoder struct {
|
|
|
|
indentString string
|
2022-05-22 11:19:59 +00:00
|
|
|
colorise bool
|
2022-11-10 08:21:18 +00:00
|
|
|
UnwrapScalar bool
|
2022-01-15 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
2022-11-10 08:21:18 +00:00
|
|
|
func NewJSONEncoder(indent int, colorise bool, unwrapScalar bool) Encoder {
|
2022-01-15 00:57:59 +00:00
|
|
|
var indentString = ""
|
|
|
|
|
|
|
|
for index := 0; index < indent; index++ {
|
|
|
|
indentString = indentString + " "
|
|
|
|
}
|
|
|
|
|
2022-11-10 08:21:18 +00:00
|
|
|
return &jsonEncoder{indentString, colorise, unwrapScalar}
|
2022-01-15 00:57:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (je *jsonEncoder) CanHandleAliases() bool {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (je *jsonEncoder) PrintDocumentSeparator(writer io.Writer) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (je *jsonEncoder) PrintLeadingContent(writer io.Writer, content string) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-08 09:56:35 +00:00
|
|
|
func (je *jsonEncoder) Encode(writer io.Writer, node *CandidateNode) error {
|
2023-04-12 09:04:02 +00:00
|
|
|
log.Debugf("I need to encode %v", NodeToString(node))
|
|
|
|
log.Debugf("kids %v", len(node.Content))
|
2022-05-22 11:19:59 +00:00
|
|
|
|
2023-04-08 09:56:35 +00:00
|
|
|
if node.Kind == ScalarNode && je.UnwrapScalar {
|
2022-11-10 08:21:18 +00:00
|
|
|
return writeString(writer, node.Value+"\n")
|
|
|
|
}
|
|
|
|
|
2022-05-22 11:19:59 +00:00
|
|
|
destination := writer
|
|
|
|
tempBuffer := bytes.NewBuffer(nil)
|
|
|
|
if je.colorise {
|
|
|
|
destination = tempBuffer
|
|
|
|
}
|
|
|
|
|
|
|
|
var encoder = json.NewEncoder(destination)
|
2022-01-15 00:57:59 +00:00
|
|
|
encoder.SetEscapeHTML(false) // do not escape html chars e.g. &, <, >
|
|
|
|
encoder.SetIndent("", je.indentString)
|
|
|
|
|
2023-04-12 09:04:02 +00:00
|
|
|
err := encoder.Encode(node)
|
2022-05-22 11:19:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if je.colorise {
|
|
|
|
return colorizeAndPrint(tempBuffer.Bytes(), writer)
|
|
|
|
}
|
|
|
|
return nil
|
2022-01-15 00:57:59 +00:00
|
|
|
}
|