go - 运行 JSON Encode 时是否可以排除已经是 JSON 的字段?

标签 go

我在 restAPI 上构建回复并使用 json.NewEncoder.Encode() 生成 JSON 回复(注意:w 是 responsewriter)。

u := Reply{Id: id, Status: "progress", Message: ""}
json.NewEncoder(w).Encode(u)

这很好用。

但是我遇到了另一种情况,其中 Message 将填充一个已经是 JSON 格式的字符串:

RetMessage := "{"debug": "on", "window": { "width": 500, "height": 500}}"
u := Reply{Id: id, Status: "progress", Message: RetMessage}
json.NewEncoder(w).Encode(u)

然后回复将是带有转义引号等的 JSON,这当然是有意义的,因为它将它解析为 JSON 的字符串,但它当然打破了这个概念,因为我希望 RetMessage 按原样传递,我想将其他人编码为 JSON。

有什么办法可以巧妙地解决这个问题? RetMessage 中的内容来自一个文件,因此我无法更改 RetMessage 有时确实已经以 JSON 编码的形式出现。

最佳答案

如果 Message 是一个完整、有效的 JSON 对象,您可以通过将其转换为类型 json.RawMessage 来完成您想要的:

type ReplyWithJSON struct {
    Id      int
    Status  string
    Message json.RawMessage
}

u := ReplyWithJSON{Id: id, Status: "progress", Message: json.RawMessage(RetMessage)}
json.NewEncoder(w).Encode(u)

这应该生成以下输出:

{"Id":123,"Status":"progress","Message":{"debug":"on","window":{"width":500,"height":500}}}

查看实际效果 on the playground .

关于go - 运行 JSON Encode 时是否可以排除已经是 JSON 的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56673851/

相关文章:

go - 在 Go 中运行 Python 命令

go - Firestore 云函数 : Get DocumentSnapshot from the event

go - mux.Vars 不工作

Golang,mongodb : getting database error details/codes

dictionary - go1.10.3中add key/value与mapassign方法的关系

go - 在 Go lang 的一个事务中使用 *sql.DB 对象运行多个函数的惯用方法

unit-testing - httptest.ResponseRecorder 没有字段或方法结果

go - 如何将一个 slice 与其他 slice 进行比较以查看内容是否匹配

http - 使用自签名证书实现 tls.Config.GetCertificate

go - 如何将 magickWand 引用传递给函数