siri
siri

Reputation: 125

Want to send empty json string "{}" instead of "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?

Upvotes: 1

Views: 3816

Answers (1)

jsageryd
jsageryd

Reputation: 4643

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

Upvotes: 1

Related Questions