我正在将 golang 与 beego 框架一起使用,但将字符串作为 json 提供时遇到了问题。
EventsByTimeRange 返回一个 json 格式的字符串值
this.Data["json"] = dao.EventsByTimeRange(request) // this -> beego controller
this.ServeJson()
"{\"key1\":0,\"key2\":0}"
我怎样才能摆脱引号?
您可以以新类型重新定义您的 json 格式字符串。这是一个小演示
package main
import (
"encoding/json"
"fmt"
)
type JSONString string
func (j JSONString) MarshalJSON() ([]byte, error) {
return []byte(j), nil
}
func main() {
s := `{"key1":0,"key2":0}`
content, _ := json.Marshal(JSONString(s))
fmt.Println(_, string(content))
}
在你的情况下,你可以这样写
this.Data["json"] = JSONString(dao.EventsByTimeRange(request))
this.ServeJson()
顺便说一句,golang-json 包添加了引号,因为它将您的字符串视为 json 值,而不是 json kv 对象。
The string you got is a fine JSON formatted value. all you need is to unmarshal it into a correct type.
See below code.
However, I think you misunderstood the ServeJson(), it returns a JSON formatted string which your client will use it, and it does that just fine (see your question).
If you remove the qoutes and slashes, You'll end up with invalid JSON string!
package main
import "fmt"
import "log"
import "encoding/json"
func main() {
var b map[string]int
err := json.Unmarshal ([]byte("{\"key1\":0,\"key2\":0}"), &b)
if err != nil{
fmt.Println("error: ", err)
}
log.Print(b)
log.Print(b["key1"])
}
You'll get: map[key1:0 key2:0]