You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go Gin API返回JSON含转义字符问题求助

问题描述

使用Gin框架开发Go语言API时,从数据库获取的数据包含一列JSON字符串。由于结构动态无法用结构体解析,采用map[string]interface{}解析修改后,通过json.Marshal转回JSON字符串,再用Gin返回响应时,字符串出现转义字符。

相关代码片段:
解析处理代码:

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)

返回响应代码:

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"
}
解决方案

问题出在重复JSON序列化:

  • 第一步用json.Marshal把grants_map转成了JSON字符串jsonBody
  • 调用c.JSON时,Gin会自动将整个gin.H对象再次序列化为JSON,导致jsonBody中的引号被转义(JSON规范要求字符串内的引号必须转义)

最优方案:直接返回原始map

去掉手动序列化的步骤,直接将grants_map传入c.JSON,让Gin完成序列化:

// 删除json.Marshal和string转换步骤
c.JSON(http.StatusCreated, gin.H{"message": "Json retrieved successfully", "data": grants_map})

备选方案:使用json.RawMessage(需保留中间字符串时)

如果必须保留中间生成的JSON字符串,用json.RawMessage包装,避免二次转义:

// 替换string转换为json.RawMessage
jsonBody := json.RawMessage(jsonString)
c.JSON(http.StatusCreated, gin.H{"message": "Json retrieved successfully", "data": jsonBody})

两种方法都能让返回的data字段呈现为正确的JSON结构,无多余转义字符。

内容的提问来源于stack exchange,提问作者Krawly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:15:34