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 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件