I want to able to send null
to the browser as JSON, if I do this:
json.NewEncoder(w).Encode(nil)
then null
will be received by the browser. However in this context:
var nearby map[string]Nearby
// ...
func GetOne(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
item := nearby[params["id"]] // item could be nil?
json.NewEncoder(w).Encode(item)
}
if nothing exists in the map, then {}
will be received by the browser instead of null
...is there some way I can send null
if the key is not in the map?
As indicated in the comments on the quesiton, the map value is a struct. A struct cannot have the value nil
.
If the intent is to write null
when there's no value in the map, then explicitly write the null
in that case:
item, ok := nearby[params["id"]]
if ok {
json.NewEncoder(w).Encode(item)
} else {
io.WriteString(w, "null")
// Can also use json.NewEncoder(w).Encode(nil), but that involves more machinery.
}