Last active
July 27, 2022 19:30
-
-
Save zachvictor/84ed5be65c6229de8fcd44f2629f893e to your computer and use it in GitHub Desktop.
Empty JSON array via Go json.Marshal or []byte literal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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