Skip to content

Commit

Permalink
Prevent html escaping (#6)
Browse files Browse the repository at this point in the history
Signed-off-by: KITAGAWA Yasutaka <[email protected]>
  • Loading branch information
kit494way authored Oct 12, 2023
1 parent a718f63 commit ab9ccda
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions jp.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -143,12 +144,11 @@ func runMain(c *cli.Context) int {
if c.Bool("unquoted") && isString {
os.Stdout.WriteString(converted)
} else {
var toJSON []byte
if c.Bool("compact") {
toJSON, err = json.Marshal(result)
} else {
toJSON, err = json.MarshalIndent(result, "", " ")
enc := newEncorder()
if !c.Bool("compact") {
enc.SetIndent("", " ")
}
toJSON, err := enc.marshal(result)
if err != nil {
errMsg("Error marshalling result to JSON: %s\n", err)
return 3
Expand Down Expand Up @@ -196,3 +196,27 @@ func enableColor(enabled bool) {
jsoncolor.DefaultTrueColor.DisableColor()
}
}

type encoder struct {
*json.Encoder
buf *bytes.Buffer
}

func newEncorder() *encoder {
buf := &bytes.Buffer{}
e := &encoder{Encoder: json.NewEncoder(buf), buf: buf}
e.SetEscapeHTML(false)
return e
}

func (e *encoder) marshal(t interface{}) ([]byte, error) {
// Encode() always append a newline.
err := e.Encode(t)
if err != nil {
return nil, err
}

// Trim the newline appended by Encode().
b := bytes.TrimSuffix(e.buf.Bytes(), []byte("\n"))
return append([]byte(nil), b...), nil
}

0 comments on commit ab9ccda

Please sign in to comment.