donqh00404
2016-01-05 06:48
浏览 73
已采纳

如何在golang中将字符串值作为json对象返回?

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?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtwxmn8741 2016-01-05 07:27
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drygauost253590142 2016-01-05 07:23

    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]

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题