dongsui0929 2018-03-14 22:26
浏览 53
已采纳

转到json中的scape html html请求

I want to scape to html some json in request but it doesn´t work, I get an error when decoding json

import (
    "html/template" 
    "encoding/json"
    "net/http"
    "io"
    "io/ioutil"
    "log"
)

func anyFunction(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Print(err)
    }
    ri, wo := io.Pipe()
    go template.HTMLEscape(wo, body)   
    var t []customStruct
    json.NewDecoder(ri).Decode(t) //error: Invalid character:'&' looking for beginning of object key string
    ...
}

The json coming from the client it´s valid because I´m using "JSON.stringify(data)" Go 1.9.4

  • 写回答

2条回答 默认 最新

  • doula2426 2018-03-15 09:17
    关注

    Do not html-escape the whole valid json payload, you are inadvertently invalidating it which causes the json decoding to fail.

    If you need to sanitize values contained in the valid json, you can do so either after you first unmarshal it, or during the unmarshaling by implementing the json.Unmarshaler interface on a custom type which could then sanitize the raw bytes of the value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?