Hi,
Problem description: curl commands returns data with escaped double quotes as below
curl -X GET http://test.com/api/appointment
{"Title":"OK","status":200,"records":2,"data":"[{\"id\":14,\"start\":\"2022-07-03T18:15:00Z\"}]
Expected output is without escaped double quotes
{“Title”:“OK”,“status”:200,“records”:2,“data”:"[{“id”:14,“start”:“2022-07-03T18:15:00Z”}]
Now lets explain program logic.
The requirement is to retrieve database records using gorm and sent back to the client as API response in json format using json.NewEncoder(w).Encode. The below structs are designed for this purpose where ApiResponse struct is used for holding both database query result(“Data”) plus meta data such as title status and records. The appointment struct is the one that holds retrieved database records which will be then later embed in to API response. Since I am using different structs for different database tables, the retrieved database records stored in respective struct will marshalled to bytes, then converts to string. Finally, writes back to http writer.
The below struct used to formulate the API response.
type ApiResponse struct {
Title string json:"Title"
Status uint json:"status"
Records int64 json:"records"
Data string json:"data"
}
The below struct holds the records retrieved from database.
type Appointment struct {
Id uint `json:"id"`
Name string `json:"name"`
Start time.Time `json:"start"`
....SKIPPING THE REST....
}
//Appointment is a struct that hold database records retrieved using gorm
//Marshal appointment to []byte to later converted to string.
data, _ := json.Marshal(appointment)
records := string(data)
//Write the response back to the client
json.NewEncoder(w).Encode(ApiResponse{Title: “OK”, Status: http.StatusOK, Records: utils.RowsAffected, Data: records })
It perfectly suits to my needs except the escaped doublequotes like below.
"[{\"id\":14,\"start\":\"2022-07-03T18:15:00Z\"}]
Please help me to find out that one or two line code that does the magic of removing \ from the output optimally.