简体   繁体   中英

Json response in Go(Gin) without escape characters

I have recently started working on Go APIs using GIN. My API is getting the data from DB with two columns where one column contains integer and other contains a json string. The json string is dynamic and hence i cant use struct for that. I am using map[string]interface{} to parse the json and modify it and then parse it back to json using json.Marshal . Now i am returning this json string as a response but getting escape characters. Have done some search regarding that, but didnt find any solution yet. Here is the part of code that i am using

var interface_obj map[string]interface{}
json.Unmarshal([]byte(grants.Data), &interface_obj)
grants_map := interface_obj["role_grants"].(map[string]interface{})
jsonString, err := json.Marshal(grants_map)
jsonBody := string(jsonString)

After this, I am returning this JSON as response in GIN framework like this

c.JSON(http.StatusCreated, gin.H{"message": "Json retrieved successfully", "data": jsonBody})

But the output i am getting is

{
    "data": "[{\"action\":\"read\",\"resource\":\"project\"},{\"action\":\"all\",\"resource\":\"users\"},{\"action\":\"all\",\"resource\":\"roles\"},{\"action\":\"all\",\"resource\":\"project-settings\"},{\"action\":\"create\",\"resource\":\"single-entity-screening\"},{\"action\":\"read\",\"resource\":\"single-entity-screening\"},{\"action\":\"create\",\"resource\":\"multi-batch-screening\"},{\"action\":\"read\",\"resource\":\"multi-batch-screening\"},{\"action\":\"read\",\"resource\":\"workspace\"},{\"action\":\"allocate\",\"resource\":\"workspace\"},{\"action\":\"update\",\"resource\":\"workspace\"},{\"action\":\"read\",\"resource\":\"case\"},{\"action\":\"allocate\",\"resource\":\"case\"},{\"action\":\"review\",\"resource\":\"case\"},{\"action\":\"update\",\"resource\":\"case\"},{\"action\":\"read\",\"resource\":\"report\"},{\"action\":\"read\",\"resource\":\"audit-trail\"},{\"action\":\"read\",\"resource\":\"delivery\"}]",
    "message": "Grants retrieved successfully"
}

I printed it on my console and it looked fine there, but causing this issue on response. Is there any way to resolve this using some standard way? Please guide Thanks

You don't need to do json.Marshal(grants_map) , just pass the value directly to gin.H and let c.JSON do the encoding, ie

gin.H{... "data": grants_map}

And in cases where you truly have raw JSON data at hand that you want to send as part of other not-yet-JSON data, you can wrap it into json.RawMessage to avoid the "double-encoding", ie

gin.H{... "data": json.RawMessage(jsonBody)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM