dongwuying0221 2018-04-02 12:47 采纳率: 0%
浏览 1088
已采纳

想要发送空的json字符串“ {}”而不是“ null”

I'm trying to handle http requests in my go api, in which i wish to send empty json string like

{"result": {}, "status": "failed"}

but when the mysql query returns zero rows, it return an output as

{"result": null, "status": "failed"}

Edit : This is the response struct i'm using:

type Resp struct {
  Result []map[string]interface{} `json:"result"`
  Status string                   `json:"status"`
}

How can i handle this situation?

  • 写回答

1条回答 默认 最新

  • douchuang4181 2018-04-02 13:02
    关注

    The Result field is a slice, which can be nil. This is rendered as null in JSON. To make it not nil, you will have to initialise it.

    In addition, since Result is a slice, it will be marshalled to a JSON array ([]), not a JSON object ({}).

    Example:

    package main
    
    import (
      "encoding/json"
      "fmt"
      "log"
      "os"
    )
    
    type Resp struct {
      Result []map[string]interface{} `json:"result"`
      Status string                   `json:"status"`
    }
    
    func main() {
      enc := json.NewEncoder(os.Stdout)
    
      fmt.Println("Empty Resp struct:")
      if err := enc.Encode(Resp{}); err != nil {
        log.Fatal(err)
      }
    
      fmt.Println()
    
      fmt.Println("Initialised Result field:")
      if err := enc.Encode(Resp{Result: []map[string]interface{}{}}); err != nil {
        log.Fatal(err)
      }
    
    }
    

    Output:

    Empty Resp struct:
    {"result":null,"status":""}
    
    Initialised Result field:
    {"result":[],"status":""}
    

    https://play.golang.org/p/9zmfH-180Zk

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗