I am using golang with beego framework and I have problem with serving strings as json.
EventsByTimeRange returns a string value in json format
this.Data["json"] = dao.EventsByTimeRange(request) // this -> beego controller
this.ServeJson()
"{\"key1\":0,\"key2\":0}"
How can I get rid of quotation marks?
you can re-define your json format string in a new type. this is a small demo
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))
}
in your case you can write like this
this.Data["json"] = JSONString(dao.EventsByTimeRange(request))
this.ServeJson()
BTW,golang-json package adds quotation marks because it treats your string as a json value,not a json k-v object.
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]