想要发送空的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?
我正在尝试在go api中处理http请求,在其中我希望发送空的json字符串,例如
{“ result”:{},“ status”:“失败”}
code> pre>
但是当mysql 查询返回零行,它以 p>
{“ result”:null,“ status”:“ failed”}}
code> pre> \返回输出 n
Edit:这是我正在使用的响应结构: p>
type Resp struct {
结果[] map [string] interface {}`json :“ result”`
状态字符串`json:“ status”`
}
code> pre>
我该如何处理这种情况? p>
答
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":""}