【发布时间】:2022-08-23 22:44:16
【问题描述】:
我最近开始使用 GIN 开发 Go API。我的 API 使用两列从 DB 获取数据,其中一列包含整数,另一列包含 json 字符串。
json 字符串是动态的,因此我不能使用 struct 。
我正在使用map[string]interface{} 解析json 并对其进行修改,然后使用json.Marshal 将其解析回json。现在我返回这个 json 字符串作为响应,但得到了转义字符。对此进行了一些搜索,但尚未找到任何解决方案。
这是我正在使用的部分代码
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)
在此之后,我在 GIN 框架中像这样返回这个 JSON 作为响应
c.JSON(http.StatusCreated, gin.H{\"message\": \"Json retrieved successfully\", \"data\": jsonBody})
但我得到的输出是
{
\"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\"
}
我将它打印在我的控制台上,它在那里看起来很好,但是在响应时导致了这个问题。 有什么方法可以使用一些标准方法来解决这个问题吗?请指导 谢谢
标签: go