This is a creation in Article, where the information may have evolved or changed.
Golang struct to json HTML without escape
Default state if struct value is HTML code output to JSON would covert to Unicode
Package Mainimport ("Encoding/json" "FMT" "OS") Func main () {type Colorgroupstruct{IDintNamestringColors []string} Group:=colorgroup{ID:1, Name:"Reds", Colors: []string{"","Red","Ruby","Maroon"},} B, err:=JSON. Marshal (group)ifErr! =Nil {fmt. Println ("Error:", Err)} Os. Stdout.write (b)}
Result would be:
{"ID":1,"Name":"Reds","Colors":[" \u003chtml\u003e \u003c/html\u003e","Red","Ruby","Maroon"]}
After change:
Package Mainimport ("Encoding/json" "FMT" "OS" "bytes") Func main () {type Colorgroupstruct{IDintNamestringColors []string} Group:=colorgroup{ID:1, Name:"Reds", Colors: []string{"","Red","Ruby","Maroon"},} B, err:=JSON. Marshal (group)ifErr! =Nil {fmt. Println ("Error:", Err)} Buffer:= &bytes. buffer{} encoder:=JSON. Newencoder (buffer) encoder. Setescapehtml (false) ERR2:=Encoder. Encode (Group) Bytes:=buffer. Bytes () fmt. PRINTLN (ERR2) OS. Stdout.write (bytes) OS. Stdout.write (b)}
https://play.golang.org/p/nWxBIc1Ig0z
Result:
<nil>{"ID":1,"Name":"Reds","Colors":["","Red","Ruby","Maroon"]}{"ID":1,"Name":"Reds","Colors":["\u003chtml\u003e \u003c/html\u003e","Red","Ruby","Maroon"]}
Example2:
Package Mainimport"FMT"Import"Encoding/json"Import"bytes"Type Trackstruct{xmlrequeststring' JSON:"XMLRequest"'}func (t*track) JSON () ([]byte, error) {buffer:= &bytes. buffer{} encoder:=JSON. Newencoder (buffer) encoder. Setescapehtml (false) Err:=Encoder. Encode (t)returnbuffer. Bytes (), Err}func main () {message:=track{} message. XMLRequest="<car><mirror>XML</mirror></car>"FMT. Println ("before Marshal", message) Messagejson, _:=message. JSON () fmt. Println ("After Marshal",string(Messagejson))}
Result
Before Marshal {<car><mirror>xml</mirror></car>}after Marshal {" XMLRequest":"<car><mirror>XML</mirror></car>" }
Refer:https://play.golang.org/p/fah-xs-qmc
Or
Package Mainimport ("Encoding/json" "Log" "bytes" "FMT") Func main () {buf:=New(bytes. Buffer) ENC:=JSON. Newencoder (BUF) Enc. Setescapehtml (false) V:= Make (map[string]string) v["Key"] ="value with <> symbols" ifERR: = Enc. Encode (&V); Err! =Nil {log. PRINTLN (Err)} FMT. Printf ("JSON codec:%v", buf. String ())}
and result:
JSON codec: {"key":"value with <> symbols"}
refer:https://play.golang.org/p/sjm3klkyw-
HTML code store in MONGO have escaped and recover to HTML code
Package Mainimport ( "fmt" "html") Func Main () { const s = ' " Fran & freddie&#; s diner" <tasty@example.com> ' FMT. Println (HTML. Unescapestring (s))}
Result
" Fran & Freddie ' s Diner " <tasty@example.com>
refer:https://golang.org/pkg/html/#example_UnescapeString