douzhuo6931 2015-11-24 08:24
浏览 20
已采纳

封送切片导致字符串

I'm trying to json encode a slice of uint8 values, but doing so results in a character string. As an example, this:

d := []uint8{1,2,3,4}
data, err := json.Marshal(d)
fmt.Println(string(data), err)

Results in:

"AQIDBA==" <nil>

I was expecting [1,2,3,4], but I am getting this odd character string instead. Here is a playground with this code on it.

  • 写回答

1条回答 默认 最新

  • dongyuji7309 2015-11-24 08:31
    关注

    That's because you use uint8 type for your numbers, and uint8 is an alias for byte (Spec: Numeric types). And by default byte arrays and slices are encoded using Base64 encoding, that's what you see ("AQIDBA==" is the Base64 encoded text of the bytes [1, 2, 3, 4]).

    Quoting from json.Marhsal() doc:

    Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object.

    Change your number type for uint or int for example, and then you will see what you expect.

    For example (Go Playground):

    type MyStruct struct {
        Data []uint
    }
    
    d := new(MyStruct)
    d.Data = []uint{1, 2, 3, 4}
    
    data, err := json.Marshal(d)
    fmt.Println(string(data), err)
    

    Output:

    {"Data":[1,2,3,4]} <nil>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度