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

huangapple go评论74阅读模式
英文:

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

问题

我正在使用golang和beego框架,我在将字符串作为json进行服务时遇到了问题。

EventsByTimeRange以json格式返回一个字符串值。

this.Data["json"] = dao.EventsByTimeRange(request) // this -> beego controller
this.ServeJson()

如何去掉引号?

英文:

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

得分: 5

你可以在一个新的类型中重新定义你的 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 键值对象。

英文:

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.

答案2

得分: 1

你得到的字符串是一个格式良好的 JSON 值。你只需要将其解组为正确的类型。

请参考下面的代码。

不过,我认为你误解了 ServeJson() 函数,它返回一个 JSON 格式的字符串,你的客户端将使用它,而且它的工作正常(参见你的问题)。

如果你移除引号和斜杠,你将得到一个无效的 JSON 字符串!

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"])
}

你将得到:

map[key1:0 key2:0]
英文:

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]

huangapple
  • 本文由 发表于 2016年1月5日 14:48:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/34605736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定