Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return string value as json object in golang?

Tags:

json

rest

go

beego

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?

like image 670
user2616232 Avatar asked Jan 05 '16 06:01

user2616232


1 Answers

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.

like image 90
JessonChan Avatar answered Sep 21 '22 09:09

JessonChan