golang struct to json html without escape
default state when struct value is html code output to json will covert to unicode
package main import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"<html> </html>", "Red", "Ruby", "Maroon"}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) }
result will be :
{"ID":1,"Name":"Reds","Colors":["\u003chtml\u003e \u003c/html\u003e","Red","Ruby","Maroon"]}
after change:
package main import ( "encoding/json" "fmt" "os" "bytes" ) func main() { type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"<html> </html>", "Red", "Ruby", "Maroon"}, } b, err := json.Marshal(group) if err != 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":["<html> </html>","Red","Ruby","Maroon"]} {"ID":1,"Name":"Reds","Colors":["\u003chtml\u003e \u003c/html\u003e","Red","Ruby","Maroon"]}
example2:
package main import "fmt" import "encoding/json" import "bytes" type Track struct { XmlRequest string `json:"xmlRequest"` } func (t *Track) JSON() ([]byte, error) { buffer := &bytes.Buffer{} encoder := json.NewEncoder(buffer) encoder.SetEscapeHTML(false) err := encoder.Encode(t) return buffer.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 main import ( "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" if err := 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 has escaped and recover to html code
package main import ( "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
有疑问加站长微信联系(非本文作者)