14
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

json.Marshalにおける特殊文字の自動エスケープ

Posted at

&、<、>、記号の自動エスケープ

jsonパッケージのMarshal関数(*Encoder.Encodeメソッドも同様)では、
一部ブラウザがjsonに含まれる上記記号をhtmlと誤認しないよう、
下記のように自動でエスケープ処理がされる。

"&" => "\u0026"
"<" => "\u003c"
">" => "\u003e"

自動エスケープを無効にするには、
EncoderのescapeHTMLプロパティをfalseに設定した上で、
Encodeメソッドを呼び出す必要があるヅラ(・Д・)
Encoder公式サイト

サンプル

encode.go
func main(){
    specialChars := struct{
        Ampersand     string    `json:"ampersand"`
        LeftAngleBracket string    `json:"left_angle_bracket"`
        RightAngleBracket string    `json:"right_angle_bracket"`
    }{
        Ampersand: "&",
        LeftAngleBracket: "<",
        RightAngleBracket: ">",
    }

    // Marshalを用いたJson変換
    bytes, _ := json.Marshal(specialChars)
    fmt.Println(string(bytes))
    // {"ampersand":"\u0026","left_angle_bracket":"\u003c","right_angle_bracket":"\u003e"}
    
    // Encodeを用いたJson変換
    encoder := json.NewEncoder(os.Stdout)
    // EscapeHTML設定値true(default)
    encoder.Encode(specialChars)
    // {"ampersand":"\u0026","left_angle_bracket":"\u003c","right_angle_bracket":"\u003e"}
    
    // EscapeHTMLをfalseに設定
    encoder.SetEscapeHTML(false)
    encoder.Encode(specialChars)
    // {"ampersand":"&","left_angle_bracket":"<","right_angle_bracket":">"}
}
14
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?