dongxixian7803 2018-10-24 02:52
浏览 44
已采纳

向浏览器发送“ null”而不是“ {}”

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?

  • 写回答

1条回答 默认 最新

  • douguo6472 2018-10-24 03:01
    关注

    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.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用