【问题标题】:Json response in Go(Gin) without escape characters没有转义字符的 Go(Gin) 中的 Json 响应
【发布时间】: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


    【解决方案1】:

    您不需要做json.Marshal(grants_map),只需将值直接传递给gin.H 并让c.JSON 进行编码,即

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

    如果您手头确实有原始 JSON 数据想要作为其他尚未 JSON 数据的一部分发送,您可以将其包装到 json.RawMessage 以避免“双重编码”,即

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

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 1970-01-01
      • 2011-07-30
      • 2011-12-17
      • 1970-01-01
      • 2015-08-06
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多