在[]字节效果很好的时候无法元帅
可以在此处找到一个可重现的示例 https://go.dev/play/play/p/p/p/wnyhehezdfxvt
我想元帅(json.marshal(...)
) json.rawmessage
字段。
type Container1 struct {
OldValue json.RawMessage `json:"old"`
NewValue json.RawMessage `json:"new"`
}
但是,它抱怨以下错误:
error calling MarshalJSON for type json.RawMessage: invalid character 'h' looking for beginning of value
更改json.rawmessage
to []字节
解决问题,但请注意,json.rawmessage
是什么但是[]字节
:
// RawMessage is a raw encoded JSON value.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawMessage []byte
我还希望能够使用json.rawmessage
,有帮助吗?谢谢!
A reproducible example can be found here https://go.dev/play/p/wNyhezDfxVt
I want to marshal (json.Marshal(...)
) a struct with json.RawMessage
fields.
type Container1 struct {
OldValue json.RawMessage `json:"old"`
NewValue json.RawMessage `json:"new"`
}
However, it complains about the below error:
error calling MarshalJSON for type json.RawMessage: invalid character 'h' looking for beginning of value
Changing json.RawMessage
to []byte
fix the issue, but note that json.RawMessage
is nothing but []byte
:
// RawMessage is a raw encoded JSON value.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawMessage []byte
I want to be still able to use json.RawMessage
, any help? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类型
JSON.RAWMESSAGE
有望容纳有效的JSON,因为它将被序列化AS-IS(RAW)。当您初始化
JSON.RAWMESSAGE
带有[] byte(“ Hello”)
的字段时,您正在转换为[]字节
,字符串文字“ Hello”
,其内容为 hello 没有引号。然后json.marshal
失败,因为您需要引号“
使其成为有效的JSON字符串。要保留引号Backticks。
仅仅是因为
json.marshal.marshal
违约切片为base64。实际上,修复了操场后,两个输出JSON看起来不同:
从
JSON.RAWMESSAGE
:来自
[]字节
:The type
json.RawMessage
is expected to hold valid JSON, because it will be serialized as-is (raw).When you initialize a
json.RawMessage
field with[]byte("hello")
, you're converting to[]byte
, the string literal"hello"
, whose content ishello
without quotes. Thenjson.Marshal
fails, because you need the quotes"
for it to be a valid JSON string. To keep the quotes, you have to use an unescaped string literal enclosed in backticks.Changing the initialization of your struct to this will work:
The
[]byte
slice inContainer2
instead doesn’t cause errors despite holding the same byte content simply becausejson.Marshal
defaults to serializing byte slices as base64.As a matter of fact, after fixing your playground, the two output JSON look different:
From
json.RawMessage
:From
[]byte
: