gobeego

Controller returns json as a string


I load a list of items from the database and would like to return it as Json. it works well but the response is not a json object, its a string with is a problem on the receiver side.

var products []*database.Product
num, err := o.QueryTable("product").Filter("date", date).All(&products)
fmt.Printf("Returned Rows Num: %d, %s", num, err)

var jsonData []byte
jsonData, err2 := json.Marshal(products)
if err2 != nil {
    fmt.Println(err)
}

this.Data["json"] = string(jsonData)
this.ServeJSON()

it returns

"[{\"Id\":\"68e7512f-ea50-45d3-a89e-845c7621b33d\",\"Producttypeid\":\"62c9ff0a-f599-4ac1-9442-ebae3bc049c1\",\"Producti...

but should be

[{"Id":"68e7512f-ea50-45d3-a89e-845c7621b33d","Producttypeid":"62c9ff0a-f599-4ac1-9442-ebae3bc049c1","Producti...

adding annotations like json:"id" does not change anything. is it a problem because it is an array? do I have to wrap that inside a struct?


Solution

  • as mentioned in the comments from Kosanovic the solution is very simple, just dont marshal yourself.

    var products []*database.Product
    num, err := o.QueryTable("product").Filter("date", date).All(&products)
    fmt.Printf("Returned Rows Num: %d, %s", num, err)
    
    this.Data["json"] = products
    this.ServeJSON()