Skip to content

Instantly share code, notes, and snippets.

@zachvictor
Last active July 27, 2022 19:30
Show Gist options
  • Save zachvictor/84ed5be65c6229de8fcd44f2629f893e to your computer and use it in GitHub Desktop.
Save zachvictor/84ed5be65c6229de8fcd44f2629f893e to your computer and use it in GitHub Desktop.
Empty JSON array via Go json.Marshal or []byte literal
package main
import (
"encoding/json"
"fmt"
"github.com/kr/pretty"
)
func main() {
// https://go.dev/play/p/AskmilHGfRf
// Not this: it becomes the JSON string "[]"
result0, _ := json.Marshal(`[]`)
fmt.Println("result0\n", string(result0[:]), "\n", result0, "\n", pretty.Sprint(result0), "\n")
// Not this: it becomes JSON null
var nilSlice []string
result1, _ := json.Marshal(nilSlice)
fmt.Println("result1\n", string(result1[:]), "\n", result1, "\n", pretty.Sprint(result1), "\n")
// This: a slice literal of any type becomes JSON []:
result2, _ := json.Marshal([]interface{}{})
fmt.Println("result2\n", string(result2[:]), "\n", result2, "\n", pretty.Sprint(result2), "\n")
// Or use a []byte literal for constants, etc.
emptyArrayJSON := []byte{91, 93}
fmt.Println("emptyArrayJSON\n", string(emptyArrayJSON[:]), "\n", emptyArrayJSON, "\n", pretty.Sprint(emptyArrayJSON), "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment