ds78662302 2018-01-05 17:03
浏览 23

golang-JSON HTML转义

Attempting to use a custom MarshalJSON to avoid escaping characters like &. It's inconvenient to use a custom encoder with the SetEscapeHTML option set in this particular case.

The function is called, and behaves as I expected. However the end result still contains the escaped form \u0026.

https://play.golang.org/p/aktPndOUmth

package main

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

type Data struct {
    URL string
}

func (d Data) MarshalJSON() ([]byte, error) {

    data := map[string]interface{}{
        "url": d.URL,
    }

    jsonData, _ := json.Marshal(data)

    jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)

    fmt.Println("func: " + string(jsonData))

    return jsonData, nil
}

func main() {

    data := Data{
        URL: "https://test.com?foo=1&bar=2",
    }

    jsonData, _ := json.Marshal(data)

     fmt.Println("main: " + string(jsonData))
}

Output:

func: {"url":"https://test.com?foo=1&bar=2"}
main: {"url":"https://test.com?foo=1\u0026bar=2"}
  • 写回答

1条回答 默认 最新

  • douyan4958 2018-07-29 11:19
    关注

    This is how I unescape sequences to make non-English letters in JSON to be readable. It will work as well for special characters like <, >, and &.

    func _UnescapeUnicodeCharactersInJSON(_jsonRaw json.RawMessage) (json.RawMessage, error) {
        str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\u`, `\u`, -1))
        if err != nil {
            return nil, err
        }
        return []byte(str), nil
    }
    
    func main() {
        // Both are valid JSON.
        var jsonRawEscaped json.RawMessage   // json raw with escaped unicode chars
        var jsonRawUnescaped json.RawMessage // json raw with unescaped unicode chars
    
        // '\u263a' == '☺'
        jsonRawEscaped = []byte(`{"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}`) // "\\u263a"
        jsonRawUnescaped, _ = _UnescapeUnicodeCharactersInJSON(jsonRawEscaped)                        // "☺"
    
        fmt.Println(string(jsonRawEscaped))   // {"HelloWorld": "\uC548\uB155, \uC138\uC0C1(\u4E16\u4E0A). \u263a"}
        fmt.Println(string(jsonRawUnescaped)) // {"HelloWorld": "안녕, 세상(世上). ☺"}
    }
    

    https://play.golang.org/p/pUsrzrrcDG-

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line