encoding/json: disable HTML escaping and omit final newline #43961
Comments
This is possible with the current api (as you've demonstrated), see |
@seankhliao my workaround is really inefficient. The Also that link doesnt really relate to this issue. Im not asking to add a new package. |
You can just slice off the last element of the byte slice. |
Here is another approach, based on your suggestion: func marshal(v interface{}) ([]byte, error) {
var dst bytes.Buffer
enc := json.NewEncoder(&dst)
enc.SetEscapeHTML(false)
err := enc.Encode(v)
if err != nil {
return nil, err
}
return dst.Bytes()[:dst.Len() - 1], nil
} Although since go/src/encoding/json/stream_test.go Lines 150 to 156 in 00f2ff5 |
Encoder enforcing a newline is unfortunate, but I agree with @seankhliao that it seems like a very minor inconvenience that doesn't warrant new API. We are aware that Marshal and Encode are weird APIs, but they are not APIs we can break. And extending Encoder with more options isn't going to be particularly better in the long run :) |
cc @dsnet |
I am encoding some JSON. I need to disable HTML escaping, and I need no trailing
newline. It seems no easy way to do this.
If I try
json#Marshal
, it does HTML escaping with no option to change. If Itry
json#Encoder.Encode
, it adds newline with no option to change. I came upwith this as a workaround:
but its pretty awkward. Also if you wanted to indent, it is difficult, since you
are now calling
json#Compact
, usingjson#Encoder.SetIndent
would be pointless, youwould have to call
json#Indent
after everything is done.https://golang.org/pkg/encoding/json
The text was updated successfully, but these errors were encountered: