How to return string value as json object in golang?

I am using golang with the beego framework and I have a problem with serving strings like 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 quotes?

+4
source share
2 answers

you can override json format string in new type. this is a small demonstration

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, the golang-json package adds quotes because it treats your string as a json value, not a json kv object.

+5
source

, , JSON. , - .

. .

, , ServeJson(), JSON, , (. ).

qoutes slashes, 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]

+1

Source: https://habr.com/ru/post/1622867/


All Articles