Skip to content

EscapeHTML=false doesn't work #397

Closed
@teou

Description

@teou

set EscapeHTML=false but the following test doesn't work:

package main

import (
        "bytes"
        "encoding/json"
        "fmt"
        "testing"

        jsoniter "github.com/json-iterator/go"
)

var marshalConfig = jsoniter.Config{
        EscapeHTML:             false,
        SortMapKeys:            true,
        ValidateJsonRawMessage: true,
}.Froze()

type Foo struct {
        Bar interface{}
}

func (f *Foo) MarshalJSON() ([]byte, error) {
        ret, err := marshalConfig.Marshal(&f.Bar)
        fmt.Println("MarshalJSON ret", string(ret), err)
        return ret, err
}

func TestFooEncode(t *testing.T) {
        foo := &Foo{
                Bar: []string{"123<ab>", "ooo"},
        }
        out, err := marshalConfig.Marshal(foo)
        if err != nil {
                t.Error("err must be nil")
                return
        }

        var stdbuf bytes.Buffer
        stdenc := json.NewEncoder(&stdbuf)
        stdenc.SetEscapeHTML(false)
        stdenc.Encode(foo)

        stdout := string(stdbuf.Bytes())
        if stdout[len(stdout)-1:] == "\n" {
                stdout = stdout[:len(stdout)-1]
        }
        bufout := string(out)
        fmt.Println("stdout", stdout)
        fmt.Println("bufout", bufout)
        if stdout != bufout {
                t.Error(fmt.Sprintf("should equal,std=%v,buf=%v", stdout, bufout))
        }
}

the output is :

MarshalJSON ret ["123<ab>","ooo"] <nil>
MarshalJSON ret ["123<ab>","ooo"] <nil>
stdout ["123<ab>","ooo"]
bufout ["123\u003cab\u003e","ooo"]
--- FAIL: TestFooEncode (0.00s)
    fail_test.go:52: should equal,std=["123<ab>","ooo"],buf=["123\u003cab\u003e","ooo"]
FAIL
exit status 1

we can see that the json was correctly marshaled in Foo.MarshalJSON, but then escaped again by standard json package?

i think pull request #337 may caused this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions