Nil Versus Empty Maps In JSON
Marshal a nil map as JSON null and an empty map as {}, and remember decoding null hands back a nil map while {} yields an initialized empty one.
Code
package main
import (
"encoding/json"
"fmt"
)
type Report struct {
// nil map 与空 map 编码结果不同:null 与 {}
Tags map[string]string `json:"tags"`
}
func main() {
var nilTags map[string]string
emptyTags := map[string]string{}
a, _ := json.Marshal(Report{Tags: nilTags})
fmt.Println("nil:", string(a))
b, _ := json.Marshal(Report{Tags: emptyTags})
fmt.Println("empty:", string(b))
// 解码方向:JSON null -> nil map(读安全写 panic);{} -> 非 nil 空 map
var fromNull Report
_ = json.Unmarshal([]byte(`{"tags": null}`), &fromNull)
var fromEmpty Report
_ = json.Unmarshal([]byte(`{"tags": {}}`), &fromEmpty)
fmt.Println("null -> nil:", fromNull.Tags == nil)
fmt.Println("{} -> initialized:", fromEmpty.Tags != nil, "len", len(fromEmpty.Tags))
}How it works
Count the function main as the entire surface area of Nil Versus Empty Maps In JSON.
Using it
Running the file prints labeled results such as nil:, empty:, null -> nil: — each operation’s effect is visible in the output.
Key statements
_ = json.Unmarshal([]byte(`{"tags": null}`), &fromNull)
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Nil Versus Empty Maps In JSON print when run?
- Running the file directly is enough — expect labeled output lines such as `nil:`, `empty:`, `null -> nil:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.