1

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?

4
  • 1
    What are the types definitions for what you’re encoding? Commented Apr 2, 2018 at 12:49
  • Are you using string for your struct that you pass to the sql driver? If so, try using mysql.NullString. Or vice versa (don't remember exactly). Commented Apr 2, 2018 at 12:49
  • @JimB, this is the response structure type Resp struct { Result []map[string]interface{} json:"result"' Status string json:"status"` } edited the same in my question Commented Apr 2, 2018 at 13:01
  • 1
    You will not be able to get an output of {} (an object). The type is a slice; so you will get a [] (an array). Commented Apr 2, 2018 at 13:05

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.