2

The following code serialises a Go slice into JSON:

package main

import (
    "encoding/json"
    "fmt"
)

type FooType uint8

const (
    Zero  FooType = 0
    One   FooType = 1
    Two   FooType = 2
    Three FooType = 3
)

func main() {
    var fooSlice []FooType
    fooSlice = make([]FooType, 1)
    fooSlice[0] = One
    bs, _ := json.Marshal(fooSlice)
    fmt.Println(string(bs))
}

Output:

"AQ=="

What I'm trying to achieve, and what I would expect to be printed is the following:

"[1]"

What is going on here?

vddox
  • 182
  • 11

1 Answers1

2

Here are some simple examples:

package main

import (
   "encoding/json"
   "strings"
)

func main() {
   { // example 1
      b := new(strings.Builder)
      json.NewEncoder(b).Encode([]uint8{1})
      println(b.String() == "\"AQ==\"\n")
   }
   { // example 2
      b := new(strings.Builder)
      json.NewEncoder(b).Encode([]byte{1})
      println(b.String() == "\"AQ==\"\n")
   }
}

and the 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 value.

https://golang.org/pkg/encoding/json#Marshal

Zombo
  • 1
  • 62
  • 391
  • 407