5

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?

1
  • 2
    Would you mind to provide some minimal reproducer, ideally via play.golang.org Commented Jan 5, 2016 at 7:22

2 Answers 2

4

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.

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

1 Comment

Thank you. This is what I was looking for.
1

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]

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.