douzhang2092 2016-05-18 15:33
浏览 230
已采纳

在Go JSON中转义unicode字符,以便输出与Python匹配

In Python 2.7, if I encode JSON I get unicode-escaped strings:

>>> import json
>>> s = {"text": "三杯雞"}
>>> print(json.dumps(s))

it gives this output:

{"text": "\u4e09\u676f\u96de"}

But in Go, similar code:

package main

import (
    "encoding/json"
    "fmt"
)

type Food struct {
    Name string `json:"name"`
}

func main() {
    food := Food{Name: "三杯雞"}
    v, _ := json.Marshal(food)
    fmt.Println(string(v))
}

Gives this:

{"name":"三杯雞"}

The Chinese characters are not escaped. I am porting API endpoints from Python to Go - how can I get it to have the same escaped output as Python?

I tried variations using strconv.QuoteToASCII, but they result in the unicode being double-escaped:

func main() {
    s := strconv.QuoteToASCII("三杯雞")
    s = strings.Trim(s, "\"")
    food := Food{Name: s}
    v, _ := json.Marshal(food)
    fmt.Println(string(v))
}

Outputs:

{"name":"\\u4e09\\u676f\\u96de"}
  • 写回答

1条回答 默认 最新

  • dqmdlo9674 2016-05-18 15:33
    关注

    One solution is to use the strconv.QuoteToASCII method inside of a custom JSON marshaler:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "strconv"
    )
    
    type Food struct {
        Name utf8String `json:"name"`
    }
    
    type utf8String string
    
    func (s utf8String) MarshalJSON() ([]byte, error) {
        return []byte(strconv.QuoteToASCII(string(s))), nil
    }
    
    func main() {
        food := Food{Name: utf8String("三杯雞")}
        v, _ := json.Marshal(food)
        fmt.Println(string(v))
    }
    

    Output:

    {"name":"\u4e09\u676f\u96de"}
    

    This has the drawback that you can't use a plain string type in the struct definition, but the final output is ASCII-quoted, just like in Python.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料